Alex Rivera | Logout

Remove keys with false values from array in PHP

Asked 2010-11-23T13:18:44.780
24

I have an associative array with a whole pile of true/false values.

I am trying to remove all keys where the values are false.

So if the array is

array(
  'key1' => true,
  'key2' => false,
  'key3' => false,
  'key4' => true
);

I want to end up with

array(
  'key1' => true,
  'key4' => true
);

How would I do this?

Edit
Report

1 Answer

-1

Arraydecleration (using PHP 5.4 array shorthand):

$arr = ['key1' => TRUE, 'key2' => FALSE, 'key3' => FALSE, 'key4' => TRUE];

Then remove all keys and values from array where value == FALSE (optionally use strict comparison "==="):

foreach ($arr as $key => $value)
    if ($value == FALSE)
        unset($arr[$key]);

Print results:

print_r($arr);

This last line prints "Array ( [key1] => 1 [key4] => 1 )".

answered 2012-03-24T12:03:26.350

Your Answer