Search code examples
phpgoto

Workaround for goto


I came to situation when I need to check if array2 has some value (randomly generated) from array1. So far I though of

redo : $id=mt_rand(0,count(array1));
foreach($array2 as $arr)
{
    if($arr[0]==$id) goto redo;
}
//Some actions if randomly generated value from array1 wasn't found in array2

But I'd really prefer not to use goto. I'm pretty sure there is some simple solution to do this without goto but I just can't think of it D:


Solution

  • You can use a numeric parameter with continue: http://www.php.net/manual/en/control-structures.continue.php

    while(true){
      $id = mt_rand(0,count(array1);
    
      foreach( $array2 as $arr )
        // restart the outer while loop if $id found
        if( $arr[0] == $id ) continue 2;
    
      // $id not found in array, leave the while loop ...
      break;
    };
    
    // ... and do the action