On the different output values of foreach and php5 in php7

encountered a weird problem while writing code


$stack = "";
$collections = [1,2,3,4,5,6];
foreach($collections as $key => $collection) {
   $stack[$key] = $collection . "_" . $key;
}
var_dump($stack);

the same code, the output in php7 is 1234567

but in php5 it is

array(7) {
[0]=>
string(3) "1_0"
[1]=>
string(3) "2_1"
[2]=>
string(3) "3_2"
[3]=>
string(3) "4_3"
[4]=>
string(3) "5_4"
[5]=>
string(3) "6_5"
[6]=>
string(3) "7_6"
}

Why is this

the sample on the Internet does not explain why, ask for the boss"s answer, thank you

Php
Mar.02,2021

$stack ='';
this sentence defines $stack as a string. The following calculations are performed according to the string type. In the case of a
string, $stack [0] is the first character of the $stack string and is only one bit long, and so on.
first loop: $tack ='1' / / $stack [0] is just a character, so there will be no trailing'_';

the point is that $stack [n] only represents the first character of the string. And it's just one character. Only the first character of the assignment will be taken.

$stack = [] is normal. One of the differences between
php7 and php5 is that variable types are more strict


did not reappear.

var_dump(PHP_VERSION,$stack);

clipboard.png

clipboard.png

php7.1

clipboard.png

Menu