相关疑难解决方法(0)

PHP array_search始终返回数组的第一个键

我最近发现在我的代码中使用array_search函数时遇到了麻烦.我正在搜索数组"$ allcraftatts"的值为"sharp".我尝试通过设置两行实验来解决问题:

$testcopy=$allcraftatts;
$testsharp=array_search("sharp", $testcopy);
Run Code Online (Sandbox Code Playgroud)

使用"print_r(get_defined_vars());" 后来,我得到了这个结果:

[testcopy] => Array
                (
                    [0] => 0
                    [1] => 0
                    [2] => 0
                    [3] => 0
                    [4] => 0
                    [5] => 0
                    [6] => Sharp Stone
                    [7] => Sharp Stones
                    [8] => stone
                    [9] => object
                    [10] => sharp
                    [11] => hard
                    [12] => 0
                    [13] => 0
                    [14] => 0
                    [15] => 0
                    [16] => 0
                    [17] => 0
                    [18] => 0
                )

[testsharp] => 0
Run Code Online (Sandbox Code Playgroud)

我确保在任何其他时间都不修改这些变量.

现在,如果我将代码更改为

$testcopy=$allcraftatts;
unset($testcopy[0]);
$testsharp=array_search("sharp", $testcopy); …
Run Code Online (Sandbox Code Playgroud)

php arrays function

6
推荐指数
1
解决办法
1293
查看次数

PHP in_array()/ array_search()奇怪的行为

我在使用PHP函数时发现了一些奇怪的行为in_array().我有这样一个数组:

$arr = [TRUE, "some string", "something else"];
Run Code Online (Sandbox Code Playgroud)

现在,如果我想检查是否"test"在数组中它显然不是,但in_array()仍然返回TRUE,为什么呢?

$result = in_array("test", $arr);
var_dump($result);  //Output: bool(true)
Run Code Online (Sandbox Code Playgroud)

使用时会发生同样的事情array_search():

$result = array_search("test", $arr);
var_dump($result);  //Output: int(0)
Run Code Online (Sandbox Code Playgroud)

我想也许数组中的值TRUE会自动导致函数为每个结果返回TRUE,而不检查数组的其余部分,但我找不到任何可能表明非常奇怪的功能的文档.

php arrays boolean

5
推荐指数
1
解决办法
1739
查看次数

标签 统计

arrays ×2

php ×2

boolean ×1

function ×1