1

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.

0

2 Answers 2

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

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 );
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.