dxcoder1
dxcoder1

Reputation: 299

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;

any help please?

Upvotes: 0

Views: 1968

Answers (3)

A simple 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";

Upvotes: 5

Leif Högberg
Leif Högberg

Reputation: 378

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.

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.

Upvotes: 0

deceze
deceze

Reputation: 522145

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.

Upvotes: 0

Related Questions