-1

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?

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Kyle
  • 1,153
  • 5
  • 28
  • 56

2 Answers2

0

To access global variable in function you must use global to tell PHP you want that:

function printArray() {
    global $city_array;

    ....
}
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
0

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);
Jamie Bicknell
  • 2,306
  • 17
  • 35