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?
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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With