Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from array using array_map

Tags:

php

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.

like image 833
Peter Cos Avatar asked Mar 16 '17 13:03

Peter Cos


People also ask

What is the use of Array_map in PHP?

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.

How do you remove null values from an array?

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.

Does array map preserve keys?

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.


2 Answers

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');
like image 73
Guillaume Sainthillier Avatar answered Sep 23 '22 05:09

Guillaume Sainthillier


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);
like image 36
Adam Patterson Avatar answered Sep 22 '22 05:09

Adam Patterson