Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove keys with false values from array in PHP

Tags:

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?

like image 833
Hailwood Avatar asked Nov 23 '10 13:11

Hailwood


People also ask

How to remove key in array PHP?

Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.

How to remove a value from an array in PHP?

In order to remove an element from an array, we can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically automatically. Function Used: unset(): This function unsets a given variable.

How to remove a row from array in PHP?

Answer: Use the PHP unset() Function If you want to delete an element from an array you can simply use the unset() function. The following example shows how to delete an element from an associative array and numeric array.

What is Array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.


1 Answers

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

array_filter()

like image 158
KingCrunch Avatar answered Sep 22 '22 13:09

KingCrunch