I use array_map to validate each array element. If it does not pass the validation it should be removed from the initial array:
$array = (123, 456);
$array = array_map(function ($e){
if( !is_numeric($e) ){
unset($e);
return; //this way i get a NULL element
}
$return $e;
}, $array);
OUTPUT: array(3) { [0]=> int(523) [1]=> int(555) [2]=> NULL }
Of course, I could add at the end something like:
$array = array_filter($array, 'strlen');
But isn't there a way to do this within array_map ?
UPDATE
Regarding this subject, i forgot to mention a case. What if i want to unset the entire array if one element didn't pass the validation? Can this be done with array_filter , array_map or anything else? I don't want to loop through the array with a for and so on.
The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.
To remove a null from an array, you should use lodash's filter function. It takes two arguments: collection : the object or array to iterate over. predicate : the function invoked per iteration.
The returned array will preserve the keys of the array argument if and only if exactly one array is passed. If more than one array is passed, the returned array will have sequential integer keys.
I think array_map is not designed for your needs, because it's apply a callback for each element of your array. But array_filter does :
$array = array_filter($array, function($e) {
return is_numeric($e);
});
Or even shorter :
$array = array_filter($array, 'is_numeric');
If you wanted to return false in your array_map
you can then apply array_filter
to clean it up.
$stores = [];
$array = array_map(function ($store) {
if ($true) {
return [
'name' => $store['name'],
];
} else {
return false;
}
}, $stores);
array_filter($array);
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