Back to questions
JuniorTheoryCommon
What does the program print?
<?php
$a = [1, 2, 3];
$b = $a;
$b[] = 4;
$b[0] = 100;
echo count($a), ' ', $a[0], ' ', count($b), ' ', $b[0], "\n";3 1 4 100
- Expecting
$bto be a second name for the same array, as in Python or JavaScript: in PHP$b = $acopies the array, so$akeeps[1, 2, 3]. - Expecting some writes to
$bto show up in$a: after$b = $athe arrays are independent, so neither$b[] = 4nor$b[0] = 100changes$a.
- When does PHP actually copy the elements: at
$b = $aor later? - Is a nested array inside
$acopied too, or shared with$b?