unfulvio
unfulvio

Reputation: 836

Skip keys in array without values in a foreach loop

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.

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;

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

thanks

Upvotes: 2

Views: 12904

Answers (1)

Mike B
Mike B

Reputation: 32145

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

Upvotes: 7

Related Questions