Skip to content

Instantly share code, notes, and snippets.

@gilbitron
Last active February 10, 2017 10:23
Show Gist options
  • Save gilbitron/5020cb89a85f66075d2a4e0128d14631 to your computer and use it in GitHub Desktop.
Save gilbitron/5020cb89a85f66075d2a4e0128d14631 to your computer and use it in GitHub Desktop.
Modifying Arrays in PHP Closures
<?php
$array = [];
(function() use ($array) {
// Add an item to the array
$array[] = 'item';
})();
var_dump($array);
/*
* Output:
*
* array(0) {
* }
*
*/
<?php
$array = [];
(function() use (&$array) { // Notice the pass by reference
// Add an item to the array
$array[] = 'item';
})();
var_dump($array);
/*
* Output:
*
* array(1) {
* [0] => string(4) "item"
* }
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment