Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
2  
Do you mean if one of the values is empty? Keys/indices cannot be empty in an array. – Josh Feb 19 '12 at 6:41
yes in that sense, sorry for not being clear – Fulvio Feb 19 '12 at 6:54

1 Answer

up vote 2 down vote accepted

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.