Skip iteration of array_map function if IF statement True

Viewed 12781

Is there a way to break or continue an iteration of the built-in method array_map() as you would in a normal for loop?

For example:

array_map(function (String s) {
    if (condition is met){
        continue;
    }
    return stuff;
}, $array_to_map);
4 Answers

No. array_map returns an array the same length as the original so you can't skip an item. i.e. Something needs to be returned on each iteration.

You could use array_filter to remove certain items.

$results = array_map(function (String s) {
    if (condition is met){
        //do stuff 
    } else {
        return false;
    }
    return stuff;
}, $array_to_map);

$results will then contain a array with the orignal number of elements in it as the $array_to_map, only with array elements set to false when the condition failed

then do.

$array_with_elements_remove = array_filter($results, function($e){
    return $e; //when this value is false the element is removed.
});

You can emulate continue by simply returning the original value.

array_map(function($var){
  if(condition)
    return $var; //continue
  return $transformedValue;
}, $arr);

However there would be no way to actually break (except disgusting things like using a StopIteration exception class)

You can try sth like this:

$newArrayWithIds = [];

array_map(function (int $id) use ($newArrayWithIds): void {
   if($id === 0) {
     return;
   }
   $newArrayWithIds[] = $id; 
}, $yourArrayWithIds);
Related