Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip iteration of array_map function if IF statement True

Tags:

php

array-map

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);
like image 503
d1596 Avatar asked Apr 21 '26 16:04

d1596


2 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.

like image 138
Ade Avatar answered Apr 23 '26 07:04

Ade


$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.
});
like image 24
Clint Avatar answered Apr 23 '26 06:04

Clint