I'll-Be-Back
I'll-Be-Back

Reputation: 10828

Reference in the foreach

Having the reference in the foreach, what does it mean and what the benefit?

For example:

foreach ($delivery as &$store) {
            $store = ClassName::FunctionName($store);
} 
unset($store);

I never really use reference when I do some coding in PHP.

Upvotes: 0

Views: 86

Answers (1)

Paul Bain
Paul Bain

Reputation: 4397

If you don't pass by reference into the foreach loop, any changes and updates won't automatically be retained in the initial data structure after the loop has completed.

For example:

$test = array('cat'=>'meow','dog'=>'woof');

foreach($test as $a){
    $a='test';
}
print_r($test);

In this case, the array will still contain:

array('cat'=>'meow','dog'=>'woof');

However in this example using references:

$test=array('cat'=>'meow','dog'=>'woof');

foreach($test as &$a){
    $a='test';
}
var_dump($test);

...the array will contain:

array('cat'=>'test','dog'=>'test');

Upvotes: 3

Related Questions