如何在PHP中跳过数组值?

时间:2014-09-11 18:01:15

标签: php arrays foreach

我需要一些帮助,我有这个阵列:

Array ( [0] => 2 [1] => 2 [2] => 1 [3] => 1 [4] => 2 [5] => 2 ) 

我正在使用foreach

foreach( $valortot as $key => $m ) {

$valortot[$key];

echo $valortot[$key];
echo "<br>";

}

它要输出:

   2 2 1 1 2 2

但我只想输出:

   2 1 2

我该怎么做?

3 个答案:

答案 0 :(得分:0)

我假设您不希望背靠背打印重复值。如果是这样,只需跟踪最后打印的值。如果当前值与之匹配,请跳过它。

$previous = '';
foreach( $valortot as $m ) {
  if($m !== $previous ) {
     echo $m ."<br>";
   };
   $previous = $m;
}

答案 1 :(得分:0)

$last_val = NULL;

foreach( $valortot as $m ) {

    if($m != $last_val){  //check if current val equals last val, if it doesn't then echo it
        echo $m;
        echo "<br>";
    }

    $last_val = $m;  //reset last val to $m to check next time around

}

答案 2 :(得分:0)

如果您的逻辑只是输出所有其他元素

for ($i = 0, $length = count($valortot); $i < $length; $i += 2) {
    echo $valortot[$i], '<br>';
}

foreach ($valortot as $i => $value) {
    if ($i % 2 == 0) {
        echo $value, '<br>';
    }
}

echo join('<br>', array_map('current', array_chunk($valortot, 2)));