To get array keys if value is not zero

2.7k views Asked by At

I have array like and used array_keys to get keys:

$arr =  array(  1 => 1,
        2 => 3,
        3 => 2,
        5 => 0,
        6 => 0 );

$new_arr = array_keys($arr);

Now, I want to get array_keys if value is not zero. How can i do this?

Please help.

3

There are 3 answers

0
Hanky Panky On BEST ANSWER

Run array_filter on your array before you get the keys; that removes the 0 values and you only get the keys you need.

$new_arr = array_keys(array_filter($arr));

Output

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
2
Pupil On

You can remove all elements with values before passing array for array_keys:

NULL
null
''
0

With the following:

array_filter($array, function($var) {
  // Remove all empty values defined in the above list.
  return !is_empty($var);
});
0
GThamizh On
$num_array = array(1,2,3,4,0,0);
$zero_val  = array_keys($num_array,!0);
print_r($zero_val);