-2

I have a PHP array $data that looks like this...

Array
(
    [section] => Array
        (
            [345dfg] => Array
                (
                    [test] => Array
                        (
                            [name] => John
                        )
                )
            [567fghj] => Array
                (
                    [test] => Array
                        (
                            [name] => Tom
                        )
                )
        )
    [othersection] => Array
        (
            [result] => 2
        )
)

I am trying to loop through each item in section so am doing this...

foreach ($data[section] as $section) {

    echo $section[test][name];

}

It is working correctly but in my error log I get...

PHP Warning:  Use of undefined constant section- assumed 'section' (this will throw an Error in a future version of PHP)

Where am I going wrong?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278

1 Answers1

6

You need to enclose array keys with a single quote as they are of type string.

So,

foreach ($data[section] as $section) {

Should be

foreach ($data['section'] as $section) {

Otherwise, without $ sign and without a single quote, section is considered as constant.

Possibilities with $data['section']:

1) $section as a Variable: $data[$section]

2) section as a Constant: $data[section]

3) section as a array key (string): $data['section']

It is always a good practice to enclose array keys with single quotes.

As by coincidence if the same constant is defined, the value of that constant may be considered as the array key.

If constant not defined, it will show a warning.

Starmixcraft
  • 389
  • 1
  • 14
Pupil
  • 23,834
  • 6
  • 44
  • 66