Please see the code below:
There are two arrays before processing arrTitle
and arrHref
,
The content of arrTitle
is as follows:
arrHref
The content is as follows:
<code class="php">//将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;</code>
Run the above PHP code to extract and remove the first element of each item in title and href. However, the problem arises. Before executing array_combine
, $arrTitle
looks like this:
However, after executing array_combine
, $arrTitle
becomes like this:
Why, the last element of $arrTitle
becomes the result of array_combine()
, but the array_combine()
function does not modify $arrTitle
?
Please see the code below:
There are two arrays before processing arrTitle
and arrHref
,
The content of arrTitle
is as follows:
arrHref
The content is as follows:
<code class="php">//将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;</code>
Run the above PHP code to extract and remove the first element of each item in title and href. However, the problem arises. Before executing array_combine
, $arrTitle
looks like this:
However, after executing array_combine
, $arrTitle
becomes like this:
Why, the last element of $arrTitle
becomes the result of array_combine()
, but the array_combine()
function does not modify $arrTitle
?
<code>**$title** = array_combine($text, $url); </code>
$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 in reference 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.