user3099298 user3099298 - 29 days ago 16
PHP Question

How to find which array key has value larger than 0

I have associative array in following way,

$data = array(
'apple'=>0,
'orange'=>5,
'mango'=>0
);


As you see
orange
is the only key has value larger than
0
. Assume
apple
has value larger than
0
.Then other values get
0
. If
mango
has value larger than
0
, then other values get
0
.

I want to find which is the key has value larger than 0.

I can write this following way but is there any easiest way to do that. Because assume if I have array with large number of element, I guess this is not a suitable way.

if(!empty($data['apple'])&&empty($data['orange'])&&empty($data['mango'])){
// apple has value larger than 0
}else if(empty($data['apple'])&&!empty($data['orange'])&&empty($data['mango'])){
// orange has value larger than 0
}else if(empty($data['apple'])&&empty($data['orange'])&&!empty($data['mango'])){
// mango has value larger than 0
}


Thank you, someone please advice me.

Answer

Use array_filter to filter out empty values.

$fruit = key(array_filter($data));

$fruit will contain the value having a number greater than zero.

If more than one key has a value greater than zero, use array_keys instead of key

$fruit = array_keys(array_filter($data));