简体   繁体   English

显示来自PHP foreach循环的特定值

[英]Display specific value from PHP foreach loop

I have a simple foreach loop in PHP. 我在PHP中有一个简单的foreach循环。 I want to get specific value from that loop. 我想从该循环中获取特定值。 I can get the 1st value with the below code but is it possible to get only 2nd or 3rd value from the same loop. 我可以使用下面的代码获取第一个值,但是有可能从同一循环中仅获取第二个或第三个值。 My code to get first value is below, 我获得第一个值的代码如下,

$i = 0;
$colors = array("red","green","blue","yellow"); 
foreach ($colors as $value)
{
  $i++;
  if($i==2) break;
  echo "$value <br>";
}

I might be wrong, but give this a try : 我可能是错的,但是尝试一下:

       foreach($colors as $value){
           $i++;
            if($i==2){
            echo $value[1].'<br>';//To get the second; $value[2] will get the third
            }
     }

You want to use continue and not break to loop through all the $colors . 您想使用continue而不是break来遍历所有$colors Also, although break is not going to be used, you want to echo before break if you were to use break as done with continue : 另外,尽管break不使用break ,但是如果要像continue一样使用breakechobreak之前echo

$i = 0;
$colors = array("red","green","blue","yellow"); 
foreach ($colors as $value)
{
  $i++;
  if($i==2) {
    echo $value, "<br />";
    continue;
  }
}

Why you need a loop if you want to get specific value? 如果要获得特定值,为什么需要循环?

$colors = array("red","green","blue","yellow"); 
echo $colors[1]; // 2nd value
echo $colors[2]; // 3rd value

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

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