vote up 1 vote down star

How can iterate with a while loop until array1 is empty.

So far based on several conditions I'm pushing elements from array1 to array2. But I want to iterate array1 until everything from array1 is in array2.

something like:

// or while everything from array1 is on array2
while(array1 is empty){

  if(somecondition1)
     array_push(array2,"Test");
     unset(array1[$i]);
  elseif(somecondition2)
     array_push(array2,"Test");
     unset(array1[$i]);    
}

Any ideas will be appreciate it!

flag
Why do you need to remove the elements from array1 (until it's empty)? Wouldn't a simple iteration suffice? – VolkerK Dec 3 at 21:36

2 Answers

vote up 1 vote down

count() would work:

while(count(array1)){

  if(somecondition1)
     array_push(array2,"Test");
  elseif(somecondition2)
     array_push(array2,"Test");

}

or use do..until

do {

  if(somecondition1)
     array_push(array2,"Test");
  elseif(somecondition2)
     array_push(array2,"Test");

} until (count(array1) == 0)
link|flag
do {...} until (...) is not correct PHP syntax. Instead, you would need to do do {...} while (count($array1) > 0);. – Jordan Ryan Moore Dec 3 at 20:24
vote up 1 vote down

Here's a test I did expanding upon your pseudo-code

$array1 = range( 1, 10 );
$array2 = array();

$i = 0;
while ( !empty( $array1 ) )
{
  if ( $array1[$i] % 2 )
  {
     array_push( $array2, "Test Even" );
     unset( $array1[$i] );
  } else {
     array_push( $array2, "Test Odd" );
     unset( $array1[$i] );
  }
  $i++;
}

echo '<pre>';
print_r( $array1 );
print_r( $array2 );
link|flag
+1 higher performance. No need to count the amount of array elements each time. – Wadih M. Dec 3 at 19:58
Just ran some benchmarks, and empty() is in average 44% faster than count() when evaluating if an array is empty or not. The benchmark i did used the same input data, and repeated the experiment the same amount of times for both cases. So if you only want to verify if the array is empty, there's absolutely no reason to use count(). Use empty(). – Wadih M. Dec 3 at 20:10

Your Answer

Get an OpenID
or
never shown

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