2

I have array in which several child arrays exists. I want to remove those arrays which specifics values are empty.

Array ( 
[9] => Array ( [address_id] => 9 [firstname] => [lastname] =>  ) 
[10] => Array ( [address_id] => 10 [firstname] => the [lastname] => king  ) 
[11] => Array ( [address_id] => 11 [firstname] => the [lastname] => queen  ) 
)

You can see firstname and lastname is empty in [9] => Array(). So how can i remove those arrays which firstname has blank? I have tried array_filter() but didn't solve my issue.

3

3 Answers 3

2

Try array_filter() with an anonymous function:

$array = array_filter($array, function($v) { return !empty($v['firstname']); });

For firstname AND lastname:

$array = array_filter($array,
                      function($v) {
                        return !empty($v['firstname']) && !empty($v['lastname']);
                      });

Keep in mind empty() is also 0, false and null, so for just an empty string you might want return $v['firstname'] !== ''; or something similar.

Sign up to request clarification or add additional context in comments.

2 Comments

what about lastname?
I don't know OP said "So how can i remove those arrays which firstname has blank?"
0

Assuming parent array is named $parent, you want to loop through and check conditionally for two empty fields, then unset indexes that match.

foreach ($parent as $key -> $value){
    if ($value['lastname'] == "" AND $value['firstname'] == ""){
        // Names not set, remove from parent array
        unset($parent[$key]);
    }
}

Comments

0

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

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

Comments

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.