I have an array outside:
$myArr = array();
I want my function to access the array outside of it so it can add values to it
function someFuntion(){ $myVal = //some processing here to determine value of $myVal $myArr[] = $myVal; }
How to give variables the correct scope for functions?
You can use anonymous functions :
Or you can use arrow functions:
By default, when you are inside a function, you do not have access to external variables.
If you want a function to be able to access an external variable, you must declare it as a global variable inside the function:
For more information, see Variable scope .
But please note that using global variables is not a good practice: this way your function is no longer independent.
A better idea is to have your function return the result :
and call the function like this:
Your function can also accept arguments and even handle arguments passed by reference :
Then, call the function like this:
With this:
For more information, you should read the Functions section, especially the following subsections: