0

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
Nikhil Kuriakose
  • 1,101
  • 2
  • 10
  • 22

1 Answers1

1

It is because you are not passing

$positiveCount = -1;

to your array_walk() function.

i think you need to do

array_walk($array, function($num) use (&$positiveCount) {
    //your code
}

Something like this.

  • Thanks!. I have seen this usage, but was trying to figure out the documentation for it. This question also gives more info. http://stackoverflow.com/questions/6320521/use-keyword-in-functions-php – Nikhil Kuriakose Jan 11 '17 at 05:08
  • You are welcome ), and yes that is a very helpful post. – SajeshBahing Jan 11 '17 at 05:18