当值已知且键是数字字符串时,如何获取数组中的键?

hgb9j2n6  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(403)

array_search似乎有一个bug,如何解决它?

$arr = [
    "0" => "Zero",
    "1" => "One",
    "2" => "Two",
];

$val = array_search("Zero", $arr, true);

echo gettype($val); // returns integer instead of string
echo $val;

我想得到“0”而不是0。我该怎么做呢?

p1iqtdky

p1iqtdky1#

如果需要字符串结果,可以进行类型转换:

$arr = [
        "0" => "Zero",
        "1" => "One",
        "2" => "Two",
    ];

    $val = (string) array_search("Zero", $arr, true);// You can typecast to String here

    echo gettype($val); // this will return string now
    echo $val;

相关问题