简体   繁体   English

在FOREACH循环中的PHP IF语句

[英]PHP IF statement within a FOREACH loop

Returning to PHP after a fair few years off, just for a personal project. 经过几年的休假后再返回PHP,仅用于个人项目。

I am having trouble getting an if statement to work inside a foreach loop. 我在让if语句在foreach循环内工作时遇到麻烦。 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 非常感谢

You must clear/reset the $value 您必须清除/重置$ value

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

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

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

You never reset $secondValue back to an empty string after the loop has completed so it always has a value (literally). 循环完成后,您再也不会将$secondValue重置$secondValue空字符串,因此它始终具有一个值(字面上)。

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

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

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

Be sure to reset $secondValue upon each iteration. 确保在每次迭代时重置$ secondValue。

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

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

echo $value . $secondValue . "<br />";
}
foreach ($test as $value){  
    if ($value == "test2"){
         echo $value . $secondValue . "<br />";
    } 
   else  
    echo $value . "<br />";
}

Please Use this code , because it's a short answer. 请使用此代码,因为这是一个简短的答案。

$test = array('test1', 'test2', 'test3', 'test4', 'test5');
foreach ($test as $value){  
    echo $value . ($value == 'test2' ? 'value' : '') . "<br />";  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM