在数组中跳过键,在foreach循环中没有值。

时间:2022-10-25 09:11:40

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.

我有一个普通的一维数组,我们叫它$myarray,有几个键从[0]到[34]。有些钥匙可能是空的。

Suppose I want to use such array in a foreach loop

假设我想在foreach循环中使用这样的数组

 $i = 1;
 $choices = array(array('text' => ' ', 'value' => ' '));
 foreach ( $myarray as $item ) :
      $count = $i++; 
      $choices[] = array('text' => $count, 'value' => $count, 'price' => $item);
 endforeach;

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...).

我希望在foreach循环中跳过所有空键,因此我在这里构建的另一个数组($ options)的行数可能比$myarray少。与此同时,正如您所看到的,我对循环进行计数,因为我需要一个增加的数字作为正在构建的新数组的一个键的值。计数应该是累进的(1..2. 3. 4.…)

thanks

谢谢

1 个解决方案

#1


5  

array_filter() will remove empty elements from an array

array_filter()将从数组中删除空元素。

You can also use continue within a loop to skip the rest of the loop structure and move to the next item:

您还可以在循环中使用continue来跳过循环结构的其余部分,并移动到下一项:

$array = array('foo', '', 'bar');

foreach($array as $value) {
  if (empty($value)) {
    continue;
  }

  echo $value . PHP_EOL;
}

// foo
// bar

#1


5  

array_filter() will remove empty elements from an array

array_filter()将从数组中删除空元素。

You can also use continue within a loop to skip the rest of the loop structure and move to the next item:

您还可以在循环中使用continue来跳过循环结构的其余部分,并移动到下一项:

$array = array('foo', '', 'bar');

foreach($array as $value) {
  if (empty($value)) {
    continue;
  }

  echo $value . PHP_EOL;
}

// foo
// bar