跳过数组的键无值foreach循环
我有一个正常的维数组,我们称之为 $ myarray中,用几个键,从[0]到[34]。某些键可以是空的,但。
I have a normal one dimensional array, let's call it $myarray, with several keys ranging from [0] to [34]. Some keys could be empty though.
假设我想在foreach循环使用这样的阵列
Suppose I want to use such array in a foreach loop
$i = 1;
$choices = array(array('text' => ' ', 'value' => ' '));
foreach ( $myarray as $item ) :
$count = $i++;
$choices[] = array('text' => $count, 'value' => $count, 'price' => $item);
endforeach;
我希望在这个foreach循环跳过所有空键,因此其他的阵列我这里建造( $选择)可能行较小量超过 $ myArray的。与此同时,虽然,你看,我数着圈,因为我需要越来越多的新阵列的关键之一值正在兴建。该计数应该是渐进的(1..2..3..4 ...)。
I'd wish to skip in this foreach loop all the empty keys, therefore the other array I'm building here ($choices) could have a smaller amount of rows than $myarray. At the same time, though, as you see, I count the loops because I need an increasing number as value of one of the keys of the new array being built. The count should be progressive (1..2..3..4...).
感谢
array_filter()
将从数组中删除空元素
array_filter()
will remove empty elements from an array
您也可以使用继续
循环中跳过循环结构的其余部分并移动到下一个项目:
You can also use continue
within a loop to skip the rest of the loop structure and move to the next item:
$array = array('foo', '', 'bar');
foreach($array as $value) {
if (empty($value)) {
continue;
}
echo $value . PHP_EOL;
}
// foo
// bar