I have an array outside:
$myArr = array();
I would like to give my function access to the array outside it so it can add values to it
function someFuntion(){
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
How do I give the function the right scoping to the variable?
By default, when you are inside a function, you do not have access to the outer variables.
If you want your function to have access to an outer variable, you have to declare it as
global, inside the function :For more informations, see Variable scope.
But note that using global variables is not a good practice : with this, your function is not independant anymore.
A better idea would be to make your function return the result :
And call the function like this :
Your function could also take parameters, and even work on a parameter passed by reference :
Then, call the function like this :
With this :
For more informations about that, you should read the Functions section of the PHP manual, and,, especially, the following sub-sections :