基于迭代位置的Foreach内部条件

时间:2016-11-17 00:34:46

标签: php

一些伪代码,如果可能,我想用Foreach执行此操作

我不知道是否可以从数组中获取位置

$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';}


}

预期结果

7
first
9
middle
10
middle
11
last

2 个答案:

答案 0 :(得分: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 :(得分:0)

独自解决,谢谢@ 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';}


}