Lee Perkins Lee Perkins - 5 months ago 11
PHP Question

PHP IF statement within a FOREACH loop

Returning to PHP after a fair few years off, just for a personal project.

I am having trouble getting an if statement to work inside a foreach loop. I am trying to get the code to echo an additional value if one of the arrays equals a certain word.

The code I have so far is:

$test = array('test1', 'test2', 'test3', 'test4', 'test5');

foreach ($test as $value){
if ($value == "test2"){
$secondValue = "value";
}

echo $value . $secondValue . "<br />";
}


I was expecting this to output the following:

test1
test2value
test3
test4
test5


However it outputs this...

test1
test2value
test3value
test4value
test5value


Any ideas as to where I am going wrong?
Many Thanks

Answer

You must clear/reset the $value

 $test = array('test1', 'test2', 'test3', 'test4', 'test5');

 foreach ($test as $value){  
   $secondValue ="";
   if ($value == "test2"){
      $secondValue = "value";
   }   

   echo $value . $secondValue . "<br />";
 }