Patrick Guinness
Patrick Guinness

Reputation: 397

Count negative values in a PHP array

I have an array which looks something like this:

array(-2, -1, 0, 1, 2, 3, 4)

I would like to count the number of negative numbers only. I can't spot where it says how to do this in the manual, is there no function to do this? Do I have to create a loop to go through the array manually?

Upvotes: 0

Views: 6753

Answers (5)

Adem Öztaş
Adem Öztaş

Reputation: 21446

You can use array_filter

function neg($var){
    if($var < 0){
        return $var;
    }        
}

$array1 = array(-2, -1, 0, 1, 2, 3, 4);
print count(array_filter($array1, "neg"));

Upvotes: 1

Christian Kiewiet
Christian Kiewiet

Reputation: 880

Try this:

$aValues = array(1, 2, 3, -1, -2, -3, 0);
echo sizeof(array_filter($aValues, create_function('$v', 'return $v < 0;')));

Upvotes: 0

Shoe
Shoe

Reputation: 76240

Do I have to create a loop to go through the array manually?

Yes, you have to do it manually by easily doing:

function count_negatives(array $array) {
    $i = 0;
    foreach ($array as $x)
        if ($x < 0) $i++;
    return $i;
}

At the end of the script $i will contain the number of negative numbers.

Upvotes: 3

adriaan
adriaan

Reputation: 1118

I should use this:

$array = array(-2, -1, 0, 1, 2, 3, 4);

function negative($int) {
     return ($int < 0);
}

var_dump(count(array_filter($array, "negative")));

Upvotes: 1

Christoph Grimmer
Christoph Grimmer

Reputation: 4313

Use array_filter http://www.php.net/manual/en/function.array-filter.php

function isnegative($value){
    return is_numeric($value) && $value < 0;
}

$arr = array_filter(array(-1,2,3,-4), 'isnegative');

echo length($arr);

Have fun.

Upvotes: 0

Related Questions