0

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?

4
  • 3
    Yes, there's no count_negative_numbers_in_array function build in. You'll have to do it yourself. Commented Feb 13, 2013 at 13:34
  • 1
    And now, seriously. Why do people try to overcomplicate things by calling several built-in functions? Just because that they have golden name "built-in"? Commented Feb 13, 2013 at 13:39
  • @PLB Sure, combining several built-in methods will of course solve the problem... :P Commented Feb 13, 2013 at 13:48
  • @deceze I was just kidding. ;) btw, people should be missing something like this (especially if they come from .net). Commented Feb 13, 2013 at 13:56

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The Op knows that, he asked for build in functionality. So answer is there is None.
Thanks for the quick answer, and saves me a bit of typing too :) Nice. Thank you Jeffery
1

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")));

1 Comment

i find this solution more elegant and still readable (event with the use a lambda function inside the array_filter)
1

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"));

Comments

0

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.

Comments

0

Try this:

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

Comments

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.