create_function in php [duplicate]
-
07-03-2021 - |
Question
Possible Duplicate:
Is there a PHP function to remove any/all key/value pairs that have a certain value from an array?
Remove zero values from a PHP array
I have one array like this.
[notify_emp] => Array
(
[224] => 0
[228] => 0
[232] => 1
[250] => 1
[350] => 1
)
I want only those keys from the array which have value set to 1 and need to remove keys that have value 0. how can I do this using create_function in php ? or is there any other way to perform the action?
Solution
Try this:
<?php
function hasOne($var)
{
// returns whether the input has 1
return($var == 1);
}
$arr= array("224"=>1, "228"=>0, "250" => 1);
print_r(array_filter($arr, "hasOne"));
?>
Which results in:
Array ( [224] => 1 [250] => 1 )
OTHER TIPS
$array = array_filter($array, create_function('$val', 'return (bool) $val;'));
...or for PHP >= 5.3:
$array = array_filter($array, function ($val) {
return (bool) $val;
});
...or simply (as @outis rightly points out) you can simply
$array = array_filter($array);
...or you could just:
foreach ($array as $k => $v) {
if (!$v) unset($array[$k]);
}
Take your pick.
However, I guess what you want is a list of items with an "on" flag, so this might be a better approach:
$flaggedAsOn = array_keys($array,'1');
If you're using PHP 5.3 then using array_filter with an anonymous function is a lot less mucking around.
If you're using a version of PHP prior to 5.3 then just implementing a function for use as a callback with array_filter is less mucking around than using create_function().
remove_unwanted ($array) {
foreach ($array as $key => $value) {
if ($array[$key] == '0') { unset($array[$key]) }
}
}