0

Some pseudo code, I wanted to do this with Foreach if possible

I don't know if is possible to get the position from the array

$num = array ( 1 => 7, 
               2 => 9,
               3 => 10,
               4 => 11,);

foreach ($num as $value) { 

if (first position) { echo $value . '<br> first <br>';} 

elseif (middle position) { echo $value . '<br> middle <br>';}

elseif (last position) { echo $value . '<br> last';}


}

Expected result

7
first
9
middle
10
middle
11
last
1
  • You can get the key, $key => $value then you could with the full array and figure out where you are. php.net/manual/en/control-structures.foreach.php The second form will additionally assign the current element's key to the $key variable on each iteration.
    – chris85
    Nov 17, 2016 at 0:37

2 Answers 2

1
$num = array ( 1 => 7, 
               2 => 9,
               3 => 10,
               4 => 11);
$i = 1;
foreach ($num as $value) { 
    if($i == 1){// if first
        echo $value.'<br> first<br>';
    }else if(count($num) == $i){// if last
        echo $value.'<br> last';
    }else{// if between first and last
        echo $value.'<br> middle<br>';
    }
    $i++;
}

//---output
/*
7
first
9
middle
10
middle
11
last
 */
1
  • dude, check my answer
    – Ricardo
    Nov 17, 2016 at 1:26
0

Solved on my own, thanks @chris85

$num = array ( 1 => 7, 
           2 => 9,
           3 => 10,
           4 => 11,);

$arrlen = count($num);

foreach ($num as $key=>$value) { 

if ($key == 1) { echo $value . '<br> first <br>';} 

elseif ($key != $arrlen) { echo $value . '<br> middle <br>';}

else {  echo $value . '<br> last';}


}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.