I have an associative array with a whole pile of true
/false
values.
I am trying to remove all keys where the 开发者_JS百科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?
$array = array_filter(array(
'key1' => true,
'key2' => false,
'key3' => false,
'key4' => true
));
array_filter()
see http://www.php.net/manual/en/function.unset.php , combine this with a foreach and you have what you need.
also, see http://www.php.net/manual/en/function.array-filter.php
for (x=0; x < array.count; x++)
{
if (key.value == false)
{
unset($arr[x]);
}
}
Just psuedocode, so I hope you know what I mean.
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 )".
精彩评论