当前位置:网站首页>Array in PHP_ The pit of merge

Array in PHP_ The pit of merge

2022-07-24 15:48:00 aben_ sky

PHP The official document is right array_merge The definition of

array_merge( array $array1[, array $...] ) : array

array_merge() Combine the cells of one or more arrays , The values in an array are appended to the back of the previous array . Returns an array as a result .

If the input array has the same string key name , Then the value after the key name will overwrite the previous value . However , If the array contains a numeric key name , The latter value will not overwrite the original value , It's attached to the back .

If only one array is given and the array is digitally indexed , The key name is re indexed in a continuous manner .

Description of pit

Look at the bold part of the document above , If you believe , And just believe what the document says , Then you're wrong .

See the example given in the document :

$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
var_dump($result);

The result is :

Array
(
    [0] => data
)

Um. , Yes , There is no problem with the example given in the document , There's really no problem .

however , If both arrays are not empty , And there are numerical subscripts , It will also re index the numerical subscript

$arr = [
    11 => 'a',
    12 => 'b'
];
$arr2 = [
    'a' => 'a1',
    14 => 'b1'
];
var_dump(array_merge($arr, $arr2));

The result is :

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  ["a"]=>
  string(2) "a1"
  [2]=>
  string(2) "b1"
}

The numerical subscripts have been reset !

so, In this case, only + To deal with it :

$result = $arr + $arr2;
原网站

版权声明
本文为[aben_ sky]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/205/202207241541347831.html