0

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++;  
}
3
  • so in an array of like [1,2,3,4] if you have the value 3 you want the 4th element? Commented Apr 19, 2018 at 8:46
  • 1
    Side note: You can remove the die();. Since you have a return before it, it will never get triggered. Commented Apr 19, 2018 at 8:47
  • @ Sérgio yes, exactly! Commented Apr 19, 2018 at 8:49

2 Answers 2

4

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;
   }  
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, Exactly what I was looking for!
@NooglersBIT Glad to hear that, don't forget to mark this at the answer.
You should probably just return or break inside the if statement, right now it will continue one more loop after a match was made.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.