开发者

php while array1 is empty iterate

开发者 https://www.devze.com 2022-12-13 16:17 出处:网络
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 i

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_pus开发者_StackOverflow中文版h(array2,"Test");
     unset(array1[$i]);    
}

Any ideas will be appreciate it!


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)


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 );
0

精彩评论

暂无评论...
验证码 换一张
取 消