0

I am trying to remove items from my array to make a new array with only items in it that have a value greater than 0. I tried stuff with the foreach loop, looked it up on internet, but nothing worked.

Here is my array

$productarray = array(
  'a' => 6,
  'b' => 0,
  'c' => 2,
  'd' => 1,
  'e' => 3,
  'f' => 4,
);

expected output:

  'a' => 6,
  'c' => 2,
  'd' => 1,
  'e' => 3,
  'f' => 4,

Thanks in advance!

3 Answers 3

1

The simplest and shortest way to do that is using the array_filter function:

$productarray = array(
  'a' => 6,
  'b' => 0,
  'c' => 2,
  'd' => 1,
  'e' => 3,
  'f' => 4,
);
$productarray = array_filter($productarray);
print_r($productarray);

outputs:

 Array ( [a] => 6 [c] => 2 [d] => 1 [e] => 3 [f] => 4 )

As you see, the key with a null equivalent value was removed.

As the documentation says:

If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed.

Sign up to request clarification or add additional context in comments.

1 Comment

@DylanStrijker in a monodimentional array sure. For a multi-dimensional array let's try it.
1

This should help you on your way:

foreach($productarray as $key => $value) {
    if($value == 0) {
        unset($productarray[$key]);
    }
}

output:

array(5) {
  ["a"]=>
  int(6)
  ["c"]=>
  int(2)
  ["d"]=>
  int(1)
  ["e"]=>
  int(3)
  ["f"]=>
  int(4)
}

Comments

0

Simply use array_search() and unset to achieve what you need, Try the following code,

<?php

$productarray = array(
  'a' => 6,
  'b' => 0,
  'c' => 2,
  'd' => 1,
  'e' => 3,
  'f' => 4,
);

if (($key = array_search(0, $productarray)) !== false) {
    unset($productarray[$key]);
}

?>

Output

Array
(
    [a] => 6
    [c] => 2
    [d] => 1
    [e] => 3
    [f] => 4
)

array_search() — Searches the array for a given value and returns the first corresponding key if successful.

unset — Unset a given variable.

Comments