Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return control from callback function or break the processing of array in middle array_filter processing

Tags:

arrays

php

Can we break execution of callback once condition satisfied with one element of array?

ex .

$a = array(1,2,3,4,5);
foreach($a as $val){

    if ($val == 3){
      break;
    }

}

if we write call back for it, it will be as below

$result = array_filter($a, function(){
      if ($val == 3){
          return true;
        }
});

In callback it will go through all array element, in spite of condition is being satisfied at 3. rest two elements 4, 5 will also go through callback

I want such function in callback, which will break callback one desired condition match and stop execution of rest of elements

Is is possible?

like image 243
Poonam Bhatt Avatar asked Jun 05 '12 05:06

Poonam Bhatt


2 Answers

You can do that with a static variable. A static variable is of local scope inside the callback function but preserves its value between calls.

It behaves like a global variable in terms of its value, but with a local scope:

$callback = function($val)
{
    static $filter = false;

    if ($val == 3) {
        $filter = true;
    }

    return $filter;        
};

This callback will return false until $val == 3. It then will return true.

like image 99
hakre Avatar answered Oct 30 '22 13:10

hakre


I dont think you can achieve this with array_filter, but you can do something like this:

$a = array(1,2,3,4,5);
try {
    array_walk($a, function($value, $key) use(&$a) {
        if ($value == 3){
            throw new Exception("condition match");
        }
        unset($a[$key]);
    });
}
catch(Exception $e) { }
var_dump($a);
like image 42
Eugene Avatar answered Oct 30 '22 12:10

Eugene