Deleting an element from an array in PHP

后端 未结 30 3858
时光说笑
时光说笑 2020-11-21 05:55

Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element?

I thought that setting it

30条回答
  •  迷失自我
    2020-11-21 06:36

    If you have to delete multiple values in an array and the entries in that array are objects or structured data, [array_filter][1] is your best bet. Those entries that return a true from the callback function will be retained.

    $array = [
        ['x'=>1,'y'=>2,'z'=>3], 
        ['x'=>2,'y'=>4,'z'=>6], 
        ['x'=>3,'y'=>6,'z'=>9]
    ];
    
    $results = array_filter($array, function($value) {
        return $value['x'] > 2; 
    }); //=> [['x'=>3,'y'=>6,z=>'9']]
    

提交回复
热议问题