2

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.

2 Answers 2

4

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Why not return instead?
Yeah, that is another way to do it.
You can learn about references here
& is reference operator, with it you are not only passing the Copy of the array's values, but the reference to the array itself.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.