PHP数组删除匹配值

时间:2012-05-30 18:02:29

标签: php

到目前为止,我在PHP中构建了这个函数,名为removeAllValuesMatching,但我似乎无法让它工作。我传递了两个参数$ arr和$ value。不知道为什么会这样。任何帮助将不胜感激。这就是我到目前为止所做的:

<?php 
$arr = array(
   'a' => "one",
   'b' => "two",
   'c' => "three",
   'd' => "two",
   'e' => "four",
   'f' => "five",
   'g' => "three",
   'h' => "two"
);
function removeAllValuesMatching($arr, $value){
 foreach ($arr as $key => $value){
 if ($arr[$key] == $value){
 unset($arr[$key]);
 }
 }
 return $arr = array_values($arr);
 }

print_r(removeAllValuesMatching($arr, "two"));

?>

2 个答案:

答案 0 :(得分:3)

你在这里覆盖$value

foreach ($arr as $key => $value){

只需将其重命名:

foreach ($arr as $key => $val) {
    if ($val == $value) {

但是,从数组中删除元素的更好方法是:

function removeAllValuesMatching(array $arr, $value) {
    $keys = array_keys($arr, $value);
    foreach ($keys as $key) {
        unset($arr[$key]);
    }
    return $arr;
}

答案 1 :(得分:0)

这是我的完整版本,没有变量碰撞和缩进:这不是一个选项,你应该总是正确缩进

<?php 
$arr = array(
    'a' => "one",
    'b' => "two",
    'c' => "three",
    'd' => "two",
    'e' => "four",
    'f' => "five",
    'g' => "three",
    'h' => "two"
);

function removeAllValuesMatching($arr, $arg){
    foreach ($arr as $key => $value){
        if ($arr[$key] == $arg){
            unset($arr[$key]);
        }
    }
    return $arr = array_values($arr);
}

print_r(removeAllValuesMatching($arr, "two"));

?>