-1

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

Wallchris
  • 33
  • 3

2 Answers2

0

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));
Amit Sharma
  • 1,775
  • 3
  • 11
  • 20
0

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

nice_dev
  • 17,053
  • 2
  • 21
  • 35