3

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

3
  • 2
    Do you mean if one of the values is empty? Keys/indices cannot be empty in an array. Commented Feb 19, 2012 at 6:41
  • yes in that sense, sorry for not being clear Commented Feb 19, 2012 at 6:54
  • I don't see any empty values in your sample data. I see values containing spaces. Commented Apr 3 at 20:53

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.