how to see if associative array key is equal to zero?

I have an associative array in PHP:

$num = array(0=>1, 1=>1, 2=>1, 3=>0);

I need to show the number in the key if the value is zero.

In this example, the result would be only number 3.

Upvotes: 1

Views: 629

Answers (2)

Rizier123
Rizier123

Reputation: 59701

This should work for you:

<?php

    $num = array(0=>1, 1=>1, 2=>1, 3=>0);

    foreach($num as $k => $v) {

        if($v == 0)
            echo $k;

    }

?>

Upvotes: 1

Kevin
Kevin

Reputation: 41873

You can use array_search() in this case:

array_search — Searches the array for a given value and returns the corresponding key if successful

$num = array(0=>1, 1=>1, 2=>1, 3=>0);
$key = array_search(0, $num);
echo $key;

FYI: that ain't an associative array.

If you want to get multiple occurances of zeroes, use array_keys() instead:

$num = array(0=>1, 1=>1, 2=>1, 3=>0, 4=>0);
$key = array_keys($num, 0);
print_r($key); // Array ( [0] => 3 [1] => 4 )

Upvotes: 2

Related Questions