简体   繁体   English

如何检查数组是否在php中包含正值

[英]how to check if array contain positive value in php

i have searched through the Internet with no luck. 我没有运气通过互联网搜索。 I have array of integers and i want to check if my array contain positive value. 我有整数数组,我想检查我的数组是否包含正值。

my array 我的数组

$Myarray = {1,3,7,-6,-9,-23,-8};

i tried to use in_array() function with no luck; 我试图没有运气地使用in_array() function

any help please? 有什么帮助吗?

A simple foreach ? 一个简单的foreach

foreach($Myarray as $v)
{
    if($v>0)
    {
        echo "Array contains a +ve value";
        break;
    }
}

Another way would be this.. 另一种方法是

$Myarray = array(-1,-3,-7,-6,-9,-23,-8);
rsort($Myarray);
echo ($Myarray[0] > 0) ? "Array contains +ve value" : "Array does not contain +ve value";

I'd use an array reduction for that: 我会为此使用数组减少:

$result = array_reduce($Myarray, function ($result, $num) { return $result || $num > 0; });
if ($result) {
    echo "Yes, there's at least one positive number in there.";
}

You'd want another solution which doesn't iterate the whole array if your array is very large, but for small arrays this does just fine. 您想要另一个解决方案,如果您的数组很大,则不对整个数组进行迭代,但是对于较小的数组而言,这样做就可以了。

Simple one liner: 简单的一个班轮:

if (count(array_filter([-23], function($v){ return ($v >= 1); }))) echo "has positive values\n";

In function form: 以函数形式:

function array_positive($arr) {
   return (bool) count(array_filter($arr, function($v){ return ($v >= 1); }));
}

php > var_dump(array_positive([-23]));
bool(false)
php > var_dump(array_positive([-23, 12]));
bool(true)

Like the other examples above it works by looping through the array. 像上面的其他示例一样,它通过遍历数组来工作。 The difference is that my example creates a new array containing only the positive values (this is the return value from array_filter), get the size of the new array and then converts that to a boolean value. 区别在于,我的示例创建了一个仅包含正值的新数组(这是array_filter的返回值),获得了新数组的大小,然后将其转换为布尔值。

You could easily change it to a function that returns only the positive values from an array: 您可以轻松地将其更改为仅返回数组中正值的函数:

function array_positive_values($arr) {
    return array_filter($arr, function($v){ return ($v >= 1); });
}

Also note that neither of these validate that the values are actually numbers. 另请注意,这些方法均不能验证值实际上是数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM