Unable to return array from function

Hi everyone,

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);

What am I do wrong?

Thank you.

$arr is not in the scope of someFunc(). you need to pass it in as parameter or import is via use.

  1. PHP is not javascript, functions can’t look to the global scope and manipulate those variables.

  2. 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 ;))

@ Dormilich,

Thank you, I see what you mean.

@rpkamp

Yes, that dot shouldn’t be there.

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’);

Yeah, baby steps :smile: I’ll google PHP pointers.

Thanks again, you have been a big help.

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);

Hi droopsnoot,

how are you doing?

Thanks for the explanation, I appreciate it! Think it will take a while longer before I master functions, though.

See you around.