Nikhil Kuriakose
Nikhil Kuriakose

Reputation: 1201

Access external variable from a function

I am trying to count the number of positive values in an input string. So, I am

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

Upvotes: 0

Views: 57

Answers (1)

SajeshBahing
SajeshBahing

Reputation: 77

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.

Upvotes: 1

Related Questions