the below code creates two paragraphs but I’m having trouble returning the $arr array, which should contain two strings - ‘Canada’ and ‘Mexico’.
$arr = array();
function someFunc($name,$location) {
echo"<p>My name is $name, and I live in $location</p>";
$arr[] .= $location;
return $arr;
}
someFunc('Bob', 'Canada');
someFunc('Pete', 'Mexico');
var_dump($arr);
PHP is not javascript, functions can’t look to the global scope and manipulate those variables.
Adding to an array is just $arr[] = , not $arr[] .=.
So this would work
function someFunc($arr, $name, $location) {
echo"<p>My name is $name, and I live in $location</p>";
$arr[] = $location;
return $arr;
}
$arr = array();
$arr = someFunc($arr, 'Bob', 'Canada');
$arr = someFunc($arr, 'Pete', 'Mexico');
var_dump($arr);
(There is a slightly easier way involving pointers, but let’s leave that for another day ;))
Brilliant, it’s working great, thank you very much. One thing I don’t get is why the function is called by assigning it to $arr, instead of just someFunc($arr, ‘Bob’, ‘Canada’);
Because you’re passing in the array as a parameter, and the function is returning the array after adding the new members to it, so you have to assign the newly-modified array to something otherwise the changes are lost. Although the sample code uses the same name for the array as the outside program, in this case it’s confusing the issue - the function is not modifying the $arr array in the global scope, it’s taking the array you passed in as the first parameter, adding the new members to it, then returning that array. To ram it home with Scallio’s code edited:
function someFunc($incomingarr, $name, $location) {
echo"<p>My name is $name, and I live in $location</p>";
$incomingarr[] = $location;
return $incomingarr;
}
$arr = array();
$arr = someFunc($arr, 'Bob', 'Canada');
$arr = someFunc($arr, 'Pete', 'Mexico');
var_dump($arr);