0

I have a simple foreach loop in PHP. 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>";
}
1
  • 2
    why you are trying loop, you can get direct like $colors[0] Commented Dec 26, 2013 at 7:24

3 Answers 3

2

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
            }
     }
Sign up to request clarification or add additional context in comments.

Comments

1

You want to use continue and not break to loop through all the $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:

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

Comments

0

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

1 Comment

My code is very long and its difficult to explain thats why i choose very simple array. Otherwise i know that in this case i don't need loop. Thanks for your answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.