This question already has an answer here:
I'm trying to add to, and print the contents of a global array that is being accessed within an individual function.
PHP
<?php
// Globals for data cache
$city_array = [];
/* printArray
* print the value of global array
*/
function printArray() {
print_r($city_array);
}
printArray();
?>
This is returning an error:
Notice: Undefined variable: city_array in /Applications/XAMPP/xamppfiles/htdocs/donorsearch/process.php on line 6
How can I get access to this global array within this local function?
</div>
To access global variable in function you must use global
to tell PHP you want that:
function printArray() {
global $city_array;
....
}
Either use global
:
$city_array = [];
function printArray() {
global $city_array
print_r($city_array);
}
printArray();
Pass via function:
function printArray($array) {
print_r($array);
}
$city_array = [];
printArray($city_array);