so I am trying to modify an array by adding key and value in a function modArr; I expect the var dump to show the added items but I get NULL. What step am I missing here?
<?php
$arr1 = array();
modArr($arr1);
$arr1['test'] = 'test';
var_dump($arr);
function modArr($arr) {
$arr['item1'] = "value1";
$arr['item2'] = "value2";
return;
}
You are modifying the array as it exists in the function scope, not the global scope. You need to either return your modified array from the function, use the
globalkeyword (not recommended) or pass the array to the function by reference and not value.To learn more about variable scope, check the PHP docs on the subject.