-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.

fat potato
  • 503
  • 1
  • 9
  • 29
  • Use `count()` with [array_filter()](http://php.net/manual/en/function.array-filter.php); or use an [array_count_values()](http://php.net/manual/en/function.array-count-values.php) to count the -1 values – Mark Baker Nov 03 '17 at 13:37
  • is there any direct approach ? – fat potato Nov 03 '17 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 – Mark Baker Nov 03 '17 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 – fat potato Nov 03 '17 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 – Mark Baker Nov 03 '17 at 14:01
  • @MarkBaker Thank you for answer – fat potato Nov 03 '17 at 14:01
  • PHP typically provides several ways of doing anything, you could equally use `count(array_diff($data, [-1]));` – Mark Baker Nov 03 '17 at 14:06
  • @MarkBaker Thank you sir! pardon my stupid questions i am very new to SO and php stuff . – fat potato Nov 03 '17 at 14:27

2 Answers2

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

Ethan
  • 4,295
  • 4
  • 25
  • 44
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);

Yonas Kassa
  • 3,362
  • 1
  • 18
  • 27