[PHP] array_filter will solve the problem of filtering 0 false

Definition and Usage

array_filter () function of the filter elements in the array using a callback function.

The function of each input key array passed to the callback function. If the callback function returns true, put the key in the array input current is returned to the resulting array. Array keys remain unchanged.

grammar:

array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )
  •  array: Required. Provisions to filter array.
  •    callback: Optional. It stipulates for the use of the callback function
  •    flag is optional. We decided to form callback parameter received:

 

problem: 

Null data filter array_filter often used, but it will default to 0, the value of this particular filter out false.

 

Method One: Direct use:

function  filtrfunction($arr){
        if($arr === '' || $arr === null){
            return false;
        }
        return true;
    }

    $data = array(
        'a'=>1,
        'b'=>0,
        'c'=>'',
        'd'=>null,
        'e'=>5,
        'f'=>false
    );
    print_r(array_filter($data,'filtrfunction'));

  

Option two: In class:

function  filtrfunction($arr){
        if($arr === '' || $arr === null){
            return false;
        }
        return true;
    }

function test(){
    $data = array(
        'a'=>1,
        'b'=>0,
        'c'=>'',
        'd'=>null,
        'e'=>5,
        'f'=>false
    );
    print_r(array_filter($data,array($this,"filterSinaList")));
}

  

 

Guess you like

Origin www.cnblogs.com/richerdyoung/p/11596781.html