Nooglers BIT
Nooglers BIT

Reputation: 71

PHP foreach loop: loop one more time after certain condition is matched

I am working with laravel and trying to get value of an array after another value using foreach loop. I am wondering what would be the best practice in solving this problem. So far I have tried this

$problems = $request->session()->get('problems');
$i = 0;
foreach ($problems as $prob) {
   $problem = $prob;
   if($request->problem_id == $prob->id){
         return 'Matched';
         die(); 
    }  
    $i++;  
}

Upvotes: 0

Views: 827

Answers (2)

killstreet
killstreet

Reputation: 1332

Eventhough @Lucarnosky code will work theres a faster way of handling this.

$problems = array_flip($request->session()->get('problems'));
if(key_exists($request->problem_id, $problems) return 'matched';
return 'problem not found';

php key_exists function

php array_flip function

Upvotes: 1

Lucarnosky
Lucarnosky

Reputation: 514

Change your foreach in something like that

$shouldQuit = false;
foreach ($problems as $prob) {
   $problem = $prob;
   if($shouldQuit)
       break;
   if($request->problem_id == $prob->id){
         $shouldQuit = true;
   }  
}

Upvotes: 4

Related Questions