Skip to content

Instantly share code, notes, and snippets.

@abznak
Created June 23, 2014 05:44
Show Gist options
  • Save abznak/7c392f92005ac3fceff3 to your computer and use it in GitHub Desktop.
Save abznak/7c392f92005ac3fceff3 to your computer and use it in GitHub Desktop.
on PHP and foreach by reference
04:46:58 tims@saw ~ $ cat test.php
<?php
$a = array(1,2,3,4);
#http://www.php.net//manual/en/control-structures.foreach.php
# "Warning Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset()"
foreach ($a as &$b) {
$b = $b * 2;
}
foreach ($a as $b) {
print "$b\n";
}
04:47:02 tims@saw ~ $ php test.php
2
4
6
6
04:47:07 tims@saw ~ $ php -v
PHP 5.4.4-14+deb7u11 (cli) (built: Jun 16 2014 09:46:53)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies
with Xdebug v2.2.1, Copyright (c) 2002-2012, by Derick Rethans
@abznak
Copy link
Author

abznak commented Jun 23, 2014

Same result with

PHP 5.5.13 (cli) (built: Jun 1 2014 21:27:10)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
with the ionCube PHP Loader v4.6.0, Copyright (c) 2002-2014, by ionCube Ltd.

@abznak
Copy link
Author

abznak commented Jun 23, 2014

It makes complete sense when you think about it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment