PHP WTF foreach loop

I have worked with PHP for a few years but recently i found a big WTF factor for me as a former Java developer. Foreach loop in PHP has not its own scope! It means this:

<?php

$name = 'Peter';
echo '$name = "'. $name . '"; before foreach.<hr>';

$names = array('Mark', 'Peter', 'John');

foreach($names as $name) {
   echo '$name = "'. $name .'"; in foreach.<br>';
}

echo '<hr>$name = "'. $name .'"; after foreach<br>';

will result in:

$name = "Peter"; before foreach.
---------------------------------------------------------
$name = "Mark"; in foreach.
$name = "Peter"; in foreach.
$name = "John"; in foreach.
---------------------------------------------------------
$name = "John"; after foreach

It means the $name variable is rewritten by foreach and it’s BAD!!!
What if i want to say “Hi Peter” after this foreach and instead of it, it will say “Hi John”.
Any suggestions how to avoid this?

Advertisements