Back to questions
JuniorTheoryCommon
What does the program print?
<?php
function push(array $list, string $x)
{
$list[] = $x;
return count($list);
}
$cart = ['tea'];
$n = push($cart, 'milk');
echo $n, ' ', count($cart), "\n";2 1
- Expecting
2 2, as if an array were passed by reference: without&the parameter is a copy, so adding to$listleaves$cartas it was. - Expecting a function to be unable to change its parameter: it may, but the change stays in its own copy and is gone after the call.
- How would you change
pushso that$cartitself gets the new element? - Why is passing a large array to a function cheap until the function writes to it?