0

I created an array outside of an functions, which means it should have global scope. I then try to loop through it from within a function, which should have access to the globally created array, but it throws an error when I attempt to do so.

$form_fields = array(
    'name',
    'locality',
    'url_slug',
    'address');

function step_1() {
    foreach($form_fields as $field) {
        echo $field . '<br />';
    }
}

step_1();

I am receiving the following error:

Undefined variable: form_fields -- at line 10

I would like to avoid using the global keyword or having to add the array as an argument for the function as I only want to read the array and not change it.

How can I access the globally created $form_fields array from within the step_1() function?

zeckdude
  • 15,877
  • 43
  • 139
  • 187

2 Answers2

2

you need to define global to $form_fields in function.

Like this:

function step_1() {
   global $form_fields;

    foreach($form_fields as $field) {
        echo $form_fields . '<br />';
    }
}
Dinesh
  • 4,066
  • 5
  • 21
  • 35
2

In your loop you want to use $field for echo and not $form_fields. If you do not want to use the global keyword:

function step_1() {
    global $form_fields;
    foreach($form_fields as $field) {
        echo $field . '<br />';
    }
}

Then the only other possibility is to access the $_GLOBALS Collection:

function step_1() {
    foreach($_GLOBALS["form_fields"] as $field) {
        echo $field . '<br />';
    }
}

Hope this answers your question.

zeckdude
  • 15,877
  • 43
  • 139
  • 187
hexerei software
  • 3,100
  • 2
  • 15
  • 19