To get the keys of an array if the value is not null

I have an array like and used array_keys to get the 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 the value is not null. How can i do this?

Please, help.

+3


source to share


3 answers


Run array_filter

on your array before you get the keys; which 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
)

      

+6


source


You can remove all elements with values โ€‹โ€‹before passing the array to 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


source


$num_array = array(1,2,3,4,0,0);
$zero_val  = array_keys($num_array,!0);
print_r($zero_val);

      

0


source







All Articles