Marty Wallace
Marty Wallace

Reputation: 35734

Array filter php multi dimensional array

Is there a built in array method in php to filter a nested associative array?

As an example:

$myArray = array(
    array('key1' => ''),
    array('key1' => 'value 1'),
    array('key1' => 'value 2'),
);

I want to remove any with and empty value - in this example the first element.

I know array_filter would do something similar with a flat array but cant find anything apart from looping over and creating my own new array. If that is the best solution then thats ok, i can do that myself. I just didnt want to possibly overlook a built in method for this.

Upvotes: 1

Views: 152

Answers (2)

Alastair F
Alastair F

Reputation: 226

There are native PHP functions you can use to do this, which is a bit simpler:

  1. remove all the keys from nested arrays that contain no value, then
  2. remove all the empty nested arrays.

    $postArr = array_map('array_filter', $postArr);
    $postArr = array_filter( $postArr );
    

Upvotes: 1

NemanjaLazic
NemanjaLazic

Reputation: 702

$myArray = array_filter($myArray, function($el){ return !empty($el['key1']); });

Upvotes: 3

Related Questions