在 PHP 的数组中获取带有条件的密钥


Get key with condition in Array in PHP

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

通过使用print_r($modValArr(;

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

我想知道这个数组中存在任何大于零的值。如果它存在,我需要它的密钥。我需要的结果是 4。

这在 PHP 中怎么可能?

这应该适合您:

(在这里我只是用 array_filter() 过滤掉 0 以下的所有值,然后用 array_keys() 获取键(

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

输出:

Array ( [0] => 4 )

查找任何大于零的值:

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;
}

例如

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

您可以更改 $val_to_check 的值以更改阈值。

试试这个。

$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;
}