I am trying to count the number of positive values in an input string. So, I am
- Converting the string to Array
- Iterate through the array and check if the num is positive
This works fine when I use a foreach loop.
But, I am trying to get this to work using the standard array functions.
$handle = fopen("php://stdin","r");
$positiveCount = -1;
fscanf($handle, "%d", $nums);
$arrayString = fgets($handle);
$array = explode(" ", $arrayString);
array_walk($array, function($num, &$positiveCount){
if($num>0){
print("In positive : {$positiveCount}\n");
$positiveCount++;
}
});
print("Total Count : {$positiveCount}");
I expected $positiveCount to be passed as reference to the function and incremented withing in.
This is my output,
$ php plusMinusNotWorking.php
4
1 2 0 -1
In positive : 0
In positive : 1
Total Count : -1
Pass by reference seems not be working here. Is it because I am using an anonymous function? My expected output is
$ php plusMinusNotWorking.php
4
1 2 0 -1
In positive : 1
In positive : 2
Total Count : 2