user1868232 user1868232 - 6 months ago 14
PHP Question

PHP Array Are all Zeros except for one. Extract that value

I have an array with values that change from time to time.
It will usually look like this.

Array ( [0] => 0 [1] => 0 [2] => 9876 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 0 [8] => 0 [9] => 0 [10] => 0 [11] => 0 )

All of the Values will be 0 except for one. (index location will change).
If more than one value is greater than 0, I need to execute a specific command.
else if only one value is greater than 0, I need to take that value and pass it to a specific command.

Answer

Try this code.

<?PHP

$array = array(
"1" => "0",
"2" => "0",
"3" => "0",
"4" => "24",
"5" => "0");

$zero_plus_keys = 0;
$zero_plus_val  = array();

foreach($array as $key => $val)
{
    if($val > 0)
    {
        $zero_plus_keys++;
        $zero_plus_val = array($key,$val);
    }
}

if($zero_plus_keys == 1)
{
    echo "In array '".$zero_plus_val[0]."' key contains Greater than zero value. the value is = '".$zero_plus_val[1]."'";
}
elseif($zero_plus_keys > 1)
{
    echo "More keys Greater than zero(0)";
}
else
{
    echo "All keys contains zero(0)s only...";
}

?>
Comments