views:

135

answers:

2

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!

+1  A: 

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)
TrippyD
`do {...} until (...)` is not correct PHP syntax. Instead, you would need to do `do {...} while (count($array1) > 0);`.
Jordan Ryan Moore
+1  A: 

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 );
Peter Bailey
+1 higher performance. No need to count the amount of array elements each time.
Wadih M.
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.