Understanding scope correctly in PHP (versus Javascript)

Viewed 325

I know that scope works differently in PHP and in Javascript.

When I first started learning Javascript (after a couple of years learning PHP), I did not initially realise that variables declared outside a function were also accessible from inside the function.

Now (after a few years of focusing much more on Javascript), I am stumped by how to return a PHP function-scope variable back to the extra-function environment.

Example:

$myArray = array();

function addItemsToMyArray($myArray) {

    $myArray[] = 'apple';
    $myArray[] = 'banana';
    $myArray[] = 'coconut';

    return $myArray;
}  

addItemsToMyArray($myArray);

echo count($myArray);    /* Gives 0 */

Why does count($myArray) give 0 instead of 3?

2 Answers

The function addItemsToMyArray() has correctly been set up to return the array to the main PHP code but you forgot to catch that return value and put it in a variable. One way to write this code and make the difference easier to see could be like this:

function addItemsToMyArray($tmpArray) {

    $tmpArray[] = 'apple';
    $tmpArray[] = 'banana';
    $tmpArray[] = 'coconut';

    return $tmpArray;
}  

$myArray = array();
$myArray = addItemsToMyArray($myArray);

echo count($myArray);    /* Gives 3 */

The variable used inside the function is a different variable than the $myArray variable outside of the function.

Unless you specify otherwise, function/method arguments are pass-by-value, meaning you get a copy of them inside the function. If you want the function to change the variable that was passed to it, you need to pass-by-reference. As described here:

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition:

Note the ampersand before $array in the doc page for sorting functions like asort() and ksort():

bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Related