Search code examples
phphtmlforeachnotice

PHP & HTML Alternate syntax for foreach: Undefined variable


EDIT: I am using wamp in these examples.

There must be something I have not figured out about the PHP & HTML alternate syntax in foreach.

The following code results in

Notice: Undefined variable: array1Value in index.php on line 8

Notice: Undefined variable: array2Value in index.php on line 12

1: <?php
2: $array1 = getArray1(); // Returns an array with values
3: $array2 = getArray2(); // Also returns an array with values
4: ?>
5:
6:    <div class="doNotRemoveDiv">
7:        <? foreach($array1 as $array1Value): ?>
8:            <?= $array1Value ?>
9:        <? endforeach; ?>
10:
11:       <? foreach($array2 as $array2Value): ?>
12:           <?= $array2Value ?>
13:       <? endforeach; ?>
14:   </div>

I've also tried

$array1 = ['value1', 'value2', 'value3'];
$array2 = ['value1', 'value2', 'value3'];

There must be something really obvious here, and I am just dumb.

P.S. I am aware I could do it like this:

6:    <div class="doNotRemoveDiv">
7:        <?php foreach($array1 as $array1Value) {
8:            echo $array1Value;
9:        } ?>
10:   </div>

And that works, but I really want to understand why my example doesn't work.


Solution

  • You are getting only one warning each, right?

    That’s because your loops did not actually execute – since you used <? only on your foreach statements, and if short_open_tags is off, that means your loop statements don’t execute at all – and so the variables are not set in the first place. But then you try to output them using <?=, and that works regardless of the aforementioned setting.

    (And after you fix that, you will still get warnings for your second loop, because in the foreach statement you used $array2Value with an uppercase V, but then $array2value with a lowercase v inside the loop.)