Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Ampersand before the variable in foreach loop [duplicate]

Possible Duplicate:
Reference - What does this symbol mean in PHP?

I need to know why we use ampersand before the variable in foreach loop

foreach ($wishdets as $wishes => &$wishesarray) {     foreach ($wishesarray as $categories => &$categoriesarray) {      } } 
like image 630
Sachin Sawant Avatar asked Jan 07 '12 11:01

Sachin Sawant


People also ask

What is & in foreach PHP?

It denotes that you pass $value by reference. If you change $value within the foreach loop, your array will be modified accordingly.

Does Break work in foreach PHP?

break ends execution of the current for , foreach , while , do-while or switch structure. break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. The default value is 1 , only the immediate enclosing structure is broken out of.

Which is faster for loop or foreach in PHP?

The foreach loop is considered to be much better in performance to that of the generic for loop. The foreach loop though iterates over an array of elements, the execution is simplified and finishes the loop in less time comparatively.


1 Answers

This example will show you the difference

$array = array(1, 2); foreach ($array as $value) {     $value++; } print_r($array); // 1, 2 because we iterated over copy of value  foreach ($array as &$value) {     $value++; } print_r($array); // 2, 3 because we iterated over references to actual values of array 

Check out the PHP docs for this here: http://pl.php.net/manual/en/control-structures.foreach.php

like image 109
Mariusz Sakowski Avatar answered Sep 19 '22 17:09

Mariusz Sakowski