user1995781
user1995781

Reputation: 19453

PHP passing array variable from function

I try to work on an global array from a function. Here is my code:

$myArray = array();
myfunc($myArray);
var_dump($myArray);

function myfunc($myArray){
    //perform some other tasks
    $myArray['name']='John';
}

But didn't work. The var_dump return empty array. How can I get the array being pass up to the global?

Thank you.

Upvotes: 2

Views: 373

Answers (2)

Tariq C
Tariq C

Reputation: 124

brenjt answer is probably the best, however the OP asked how to access the global variable. You could access the $myArray globally using the global keyword, but you wouldn't pass that array into the function.

$myArray = array();
myfunc($myArray);
var_dump($myArray);

function myfunc(){
    global $myArray; 

    //perform some other tasks
    $myArray['name']='John';
}

This would NOT be the best method for accessing the array. You should use the example by brenjt, but I wanted to show that this is also possible.

Upvotes: 1

brenjt
brenjt

Reputation: 16297

You need to pass is as a reference &

Try doing this:

function myFunc(&$myArray){
    //perform some other tasks
    $myArray['name']='John';
}

You could also return it as such:

$myArray = array();
$myArray = myfunc($myArray);
var_dump($myArray);

function myfunc($myArray){
    //perform some other tasks
    $myArray['name']='John';
    return $myArray;
}

Upvotes: 4

Related Questions