-3

For example i have an array like this [-1,-1,-1,-1,-1,-1,2.5,-1,-1,8.3] I want to count the element which are not -1 like except of the -1. Is there any function in php to get this ? One approach which i think is

Count the total array - count of the -1 in the array.

how can we achieve this.

P.S : please provide me a comment why this question deserve negative vote.

8
  • Use count() with array_filter(); or use an array_count_values() to count the -1 values Commented Nov 3, 2017 at 13:37
  • is there any direct approach ? Commented Nov 3, 2017 at 13:40
  • How direct do you want? count() with array_filter() is just two function calls that can be nested $result = count(array_filter($myArray), function($value) { return $value != -1; });.... sorry that PHP doesn't provide a countExcludingValuesOfMinusOne() function so that you can make it a single function call Commented Nov 3, 2017 at 13:41
  • yeah i understand but php provides like a in_array function so thats why. i think there is a function for that also Commented Nov 3, 2017 at 13:45
  • Yes, in_array() would tell you if a value of -1 exists in the array.... it doesn't count them for you Commented Nov 3, 2017 at 14:01

2 Answers 2

1

Like @MarkBaker said, PHP doesn't have a convenient function for every single problem, however, you could make one yourself like this:

$arr = [-1,-1,-1,-1,-1,-1,2.5,-1,-1,8.3];

function countExcludingValuesOfNegativeOne ($arr) {
    return count($arr) - array_count_values(array_map('strval', $arr))['-1'];
}

echo countExcludingValuesOfNegativeOne($arr); // Outputs `2`.

It just counts the whole array, then subtracts the number of negative 1s in the array. Because PHP throws an error if any element in the array isn't a string 1 when using array_count_values, I've just converted all elements of the array to a string using array_map('strval', $arr) 2

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

Comments

0

you can use a for loop counter skipping for a specific number.

function skip_counter($array,$skip){
    $counter = 0;
    foreach ($array as $value) {
        if ($value != $skip) $counter++;
    }
return $counter;
}

then you call skip_counter($your_list, $number_to_be_skipped);

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.