I have an Associative array in PHP and want to remove all values which have the associated value of 0
Array ( [item1] => 0 [item2] => 10 [item5] => 0 [item10] => 10 [item12] => 5 )
Thank you
I have an Associative array in PHP and want to remove all values which have the associated value of 0
Array ( [item1] => 0 [item2] => 10 [item5] => 0 [item10] => 10 [item12] => 5 )
Thank you
you can do this simply using array_filter
$data = Array ( 'item1' => 0 ,'item2' => 10, 'item5' => 0, 'item10' => 10, 'item12' => 5 );
echo '<pre>';print_r(array_filter($data));
Well, there are a lot of ways to achieve this, out of which two I have mentioned below:
Snippet:
<?php
$arr = [
'item1' => 0,
'item2' => 10,
'item5' => 0,
'item10' => 10,
'item12' => 5,
'item120' => false,
];
$filtered = array_filter($arr,function($value){
return $value !== 0;
});
print_r($filtered);
Demo: https://3v4l.org/fMsHt
Snippet:
<?php
$arr = [
'item1' => 0,
'item2' => 10,
'item5' => 0,
'item10' => 10,
'item12' => 5,
'item120' => false,
];
print_r(array_diff($arr,[0]));
Demo: https://3v4l.org/3YHiX