So im learning about passing by reference, what i dont understand is this, do i need to use pass by reference on functions? Like this
$items = [1,2,3,4,5];
function my_func(&$items) {
$items[] = 6;
}
my_func($items);
var_dump($items);
It will output
array(6) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) [5]=> int(6) }
I have seen people adding values to array by reference like this
class play {
public function test() {
$items = [1,2,3,4,5];
foreach($items as &$item) {
$item[] = 6;
}
return $items;
}
}
$play = new play;
$play->test();
then i get Warning:
Cannot use a scalar value as an array in
Is there a way in a loop to add a value by reference outside a function?
$item = 6;, which will replace every element of the array with6. - Barmar