Is there a PHP function to remove any/all key/value pairs that have a certain value from an array?

前端 未结 5 1994
予麋鹿
予麋鹿 2021-01-26 11:27

I think questions like this are the reason why I don\'t like working with PHP. The manual is good, if you can find what you are looking for. After reading through the Array Func

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-26 11:29

    array_filter does this for you. You just need to provide a filter callback function:

    function myFilter($Value){
       if($Value == 'red'){
          return false;
       }
       return true;
    }
    
    $Values = array("a" => "green", "red", "bicycle", "red");
    
    $Values = array_filter($Values, 'myFilter');
    

    returns:

    array {
      ["a"] => "green"
      [1]   => "bicycle"
    }
    

    The filter function should return true for values you want to keep and false for those you wish to remove. Then just go ahead and use array_values to re-index the array. e.g.

    $Values = array_values(array_filter($Values, 'myFilter'));
    

    If you are doing this within an object and you want to call a filter method within the object you can use this form for the callback:

    array_filter($Values, array($this,'myFilter'));
    

提交回复
热议问题