Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit from array iteration functions (array_reduce) in PHP

I'm having an array_reduce function which I am willing to exit when specific criteria is met.

$result = array_reduce($input, function($carrier, $item) {
  // do the $carrier stuff
  if (/* god was one of us */) {
    break; //some break analogue
  }
  return $carrier;
});

How do I achieve this? Or should I use foreach instead?

like image 746
Konstantin Bodnia Avatar asked May 04 '15 14:05

Konstantin Bodnia


Video Answer


1 Answers

array_reduce is used to write functional-style code which always iterates over the full array. You can either rewrite to use a regular foreach loop to implement short circuiting logic, or you can simply return the current $carrier unmodified. This will still iterate over your full array, but it will not alter the result (as you said, this is more alike to continue)

like image 191
knittl Avatar answered Oct 24 '22 17:10

knittl