3

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.

Bhumi Shah
  • 9,323
  • 7
  • 63
  • 104

3 Answers3

8

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
)
Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
0

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);
});
Pupil
  • 23,834
  • 6
  • 44
  • 66
  • That callback is not needed, will do even without it. Its the default behavior: `If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed. ` – Hanky Panky Nov 19 '14 at 05:16
  • @Hanky웃Panky, that is a good learning for me. This is why I love stackoverflow. :) – Pupil Nov 19 '14 at 05:27
0
$num_array = array(1,2,3,4,0,0);
$zero_val  = array_keys($num_array,!0);
print_r($zero_val);
GThamizh
  • 2,054
  • 3
  • 17
  • 19