0

I have two arrays, I want to return an array which contains only the keys that are in my template:

$protected template = ['name' => 'john', 'age'=> 10];

public function merge($params){

    $arr = array_intersect_key($params, $this->template);

}

The above works, but I would also like to filter out keys where the value is empty.

So if I pass in:

[name => 'jeff', age => '']

It would just filter out an array of:

[name => 'jeff']

Is there a way to do this or would it be best to just loop through the array and do an empty check?

panthro
  • 22,779
  • 66
  • 183
  • 324

1 Answers1

1

you can use array_filter to remove empty elements.

$template = array_filter($template, 'strlen')
Whiteulver
  • 828
  • 7
  • 12
  • 3
    This will remove age in this case also ['name' => 'john', 'age'=> '0']; – jonju Aug 12 '16 at 14:45
  • 1
    Are you sure? http://sandbox.onlinephpfunctions.com/code/d90c1c83f0a44668b5240cfd02d826576b838d49 – Whiteulver Aug 12 '16 at 14:48
  • Yes I am. You need a callback function to handle this – jonju Aug 12 '16 at 14:50
  • 1
    Please, do not downvote if you have not run the code first... The comment of @jonju is totaly wrong and confusing. Check the link i sent you above. It runs as expected – Whiteulver Aug 12 '16 at 14:50
  • I did not down vote. Why is this wrong? **If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed.**. http://php.net/manual/en/function.array-filter.php – jonju Aug 12 '16 at 14:51
  • I have pass the `strlen` callback to array_filter. @jonju did not mean you as downvoter but this was a general request. Also check this http://php.net/manual/en/function.array-filter.php#111091 – Whiteulver Aug 12 '16 at 14:53