Home>Article>Backend Development> Why does PHP use the array_combine method to affect the original array?
Please see the code below:
There are two arrays before processingarrTitle
andarrHref
,
The content ofarrTitle
is as follows:
arrHref
The content is as follows:
//将title数组中首元素取出,作为栏目标题 foreach ($arrTitle as &$title) { $text [] = $title[0]; unset($title[0]); } //将href数组中首元素取出,作为栏目url foreach ($arrHref as &$href) { $url [] = $href[0]; unset($href[0]); } print_r($arrTitle); //重新组织title项 $title = array_combine($text, $url); print_r($arrTitle);die;
Run the above PHP code to extract and remove the first element of each item in title and href. However, the problem arises. Before executingarray_combine
,$arrTitle
looks like this:
However, after executingarray_combine
,$arrTitle
becomes like this:
Why, the last element of$arrTitle
becomes the result ofarray_combine()
, but thearray_combine()
function does not modify$arrTitle
?
Please see the code below:
There are two arrays before processingarrTitle
andarrHref
,
The content ofarrTitle
is as follows:
arrHref
The content is as follows:
//将title数组中首元素取出,作为栏目标题 foreach ($arrTitle as &$title) { $text [] = $title[0]; unset($title[0]); } //将href数组中首元素取出,作为栏目url foreach ($arrHref as &$href) { $url [] = $href[0]; unset($href[0]); } print_r($arrTitle); //重新组织title项 $title = array_combine($text, $url); print_r($arrTitle);die;
Run the above PHP code to extract and remove the first element of each item in title and href. However, the problem arises. Before executingarray_combine
,$arrTitle
looks like this:
However, after executingarray_combine
,$arrTitle
becomes like this:
Why, the last element of$arrTitle
becomes the result ofarray_combine()
, but thearray_combine()
function does not modify$arrTitle
?
**$title** = array_combine($text, $url);
$title here has the same name as $title in the loop above, just change the name. There is no block scope in php.
This bug has been resolved. Thanks to @whyreal for pointing out the duplicate name issue.
Since in the foreach loop, the array is traversed inreference mode
, when the loop ends,$title
points to the last set of elements of$arrTitle
.
Since PHP does not have a block-level scope, in $title = array_combine($arr1, $arr2), then the $title also modifies the last group of elements it points to$arrTitle
, resulting in a bug.
Modify the name behind$title
to eliminate this bug.