I'd like to remove an array item by value. Key cannot be specified. Here is the array. I have sorted the array by value, numeric descending.
Array
(
[this] => 15
[that] => 10
[other] => 9
[random] => 8
[keys] => 4
)
If I want to unset all items that have a value less than 10. How do I do that?
使用array_filter
函数:
$a = array_filter($a, function($x) { return !($x < 10); });
foreach($array as $key => $value)
if( $value < 10 )
unset($array[$key])
Assuming that all values are ints:
for (i=9;i>=0;i--)
{
while (array_search($i, $assocArray) !== false)
{
unset($assocArray[array_search($i, $assocArray)]);
}
}
There probably are more elegant ways of doing this, but fever has a firm grip on my brain :)
knittl's answer is correct, but if you're using an older version of PHP, you can' t use the anonymous function, just do:
function filterFunc($v)
{
return $v >= 10;
}
$yourArray = array_filter($yourArray,'filterFunc');
Credit to Knittl
$test = array(
"this" => 15,
"that" => 10,
"other" => 9,
"random" => 8,
"keys" => 4
);
echo "pre: ";print_r($test);
pre: Array ( [this] => 15 [that] => 10 [other] => 9 [random] => 8 [keys] => 4 )
Run this code:
foreach($test AS $key => $value) {
if($value <= 10) {
unset($test[$key]);
}
}
Results are:
echo "post: ";print_r($test);
post: Array ( [this] => 15 )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.