PHP array_splice 循环内未按预期工作

PHP array_splice within loop not working as desired

我正在使用以下代码,在这一点上一切似乎都很好。

$colors = array('red', 'yellow', 'blue');
$replacements = array('yellow' => array(1, 1), 'blue' => array('black','orange'));
foreach ($replacements as $color => $replace) {
    $position = array_search($color, $colors);
    array_splice($colors, $position, 1, $replace);
}

$颜色的结果:

Array
(
    [0] => red
    [1] => 1
    [2] => 1
    [3] => black
    [4] => orange
)

这就是我遇到的问题。如果我只是将 $replacements 数组更改为以下内容(请注意黄色数组值已更改):

$replacements = array('yellow' => array(0, 1), 'blue' => array('black','orange'));

然后再次 运行 代码我得到以下意外结果:

Array
(
    [0] => red
    [1] => black
    [2] => orange
    [3] => 1
    [4] => blue
)

上面的结果不是我所期望的。 array_splice 函数似乎在传递零 (0) 值时出现某种问题。

期望的结果如下:

Array
(
    [0] => red
    [1] => 0
    [2] => 1
    [3] => black
    [4] => orange
)

知道可能出了什么问题以及如何解决这个问题吗?

您 运行 违反了 array_search() 松散类型比较的默认行为。在PHP、any string is considered equal to integer zero时做松散比较(==)而不是严格比较(===)。

所以在第二次替换时,PHP 认为 'blue' 与第一次替换中的 0 大致相等,并替换 'black','orange' 其中 0曾经。

var_dump('blue' == 0);
// bool(true)
var_dump('blue' === 0);
// bool(false)

要使 array_search() 严格比较,请将 TRUE 作为其第三个参数传递。然后你会得到预期的结果。

$colors = array('red', 'yellow', 'blue');
$replacements = array('yellow' => array(0, 1), 'blue' => array('black','orange'));
foreach ($replacements as $color => $replace) {
    // Use a strict comparison with TRUE as the 3rd arg
    $position = array_search($color, $colors, TRUE);
    array_splice($colors, $position, 1, $replace);
}

print_r($colors);
Array
(
    [0] => red
    [1] => 1
    [2] => 0
    [3] => black
    [4] => orange
)