1
 if ($totalModuletest>0){
     if (in_array(1, $modValArr, true)){
         echo "1.13 found with strict check\n";
      }
 }
 else{
      $aVal = 0;
 }

By using print_r($modValArr);

Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 1[5])

I want to know any value exist greater than zero in this array. If it exists I need its key. The result I need is 4.

How is this possible in PHP?

3
  • 1. How does your array structure looks like? 2.So you want to filter all values out which are greater than 0 and then get the keys from all these values? Commented Apr 2, 2015 at 11:37
  • 1
    @Sona but within your array no value is greater than 0 Commented Apr 2, 2015 at 11:40
  • In this example at the end $modValArr is exactly equal to $moduleArr - is there a reason you are copying it like this? Commented Apr 2, 2015 at 11:41

3 Answers 3

5

This should work for you:

(Here I just filter all values below 0 out with array_filter() and then just get the keys with array_keys())

<?php

    $arr = [0, 0, 0, 0, 1, ""];
    $result = array_keys(array_filter($arr, function($v){
        return $v > 0;
    }));

    print_r($result);

?>

output:

Array ( [0] => 4 )
Sign up to request clarification or add additional context in comments.

2 Comments

Nice, but no need for the function. array_filter will filter out 0, '', null, false.
@AbraCadaver you're right, but I think OP wants to change the number(X) $v > X as he wants it to have, so it wouldn't work with $v > 3 or so that's why I wrote it that way from the start
0

To find any value greater than zero:

function find_keys_greater_than(Array $input_array, $val_to_check = 0){
    $keys_greater_than = [];    
    foreach ($input_array as $key => $value){
        if ($value > $val_to_check){
            $keys_greater_than[] = $key;
        }
    }
    return $keys_greater_than;
}

E.g.

$input_array=[0, 0, 4, 0, 1, 0];
$keys_greater_than_zero = find_keys_greater_than($input_array, 0);
// output: [2, 4]

You can change the value of $val_to_check to alter your threshold.

Comments

0

Try this..

$yourarray=array(0,0,2,0,4,1);
//array_filter used to remove 0,null,empty array.so you will get non empty or grater then 0 value of array
$newvalue=array_filter($yourarray);

foreach($newvalue as $key=>$value)
{
 echo "value:".$value;
 echo "Key:".$key;
}

3 Comments

This is a string and NOT an array!
I have posted example array
And now it's even worse, because this will throw you a fatal error!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.