note 110558 modified in class.arrayobject by danbrown
| From: | danbrown@php.net | Date: | Thu, 06 Dec 2012 14:22:37 +0000 |
| Subject: | note 110558 modified in class.arrayobject by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-192330@lists.php.net to get a copy of this message | ||
Long story short b/c arrays by default are passed by value, if you pass an array to a function, the
function works on a copy of the array while the original array remains unaltered by the function.
You may cause a change to the array to be reflected in the original array by having the function
return the altered array and assign it to the variable for the original array, as follows:
<?php
function my_array_modify($data) {
$data['b'] = 2;
return $data;
}
$regularArray = array();
$regularArray['a'] = 1;
$regularArray = my_array_modify($regularArray);
var_dump($regularArray['b']); // 2
?>
Or, you may explicitly pass the array by reference in which case there is no need for the function
to return the array since the change will have effected the original array, as follows:
<?php
function my_arrayref_modify(&$data) {
$data['bb'] = 22;
}
my_arrayref_modify($regularArray);
var_dump($regularArray['bb']); // 22
?>
--was--
Long story short b/c arrays by default are passed by value, if you pass an array to a function, the
function works on a copy of the array while the original array remains unaltered by the function.
You may cause a change to the array to be reflected in the original array by having the function
return the altered array and assign it to the variable for the original array, as follows:
function my_array_modify($data) {
$data['b'] = 2;
return $data;
}
$regularArray = array();
$regularArray['a'] = 1;
$regularArray = my_array_modify($regularArray);
var_dump($regularArray['b']); // 2
Or, you may explicitly pass the array by reference in which case there is no need for the function
to return the array since the change will have effected the original array, as follows:
function my_arrayref_modify(&$data) {
$data['bb'] = 22;
}
my_arrayref_modify($regularArray);
var_dump($regularArray['bb']); // 22
http://php.net/manual/en/class.arrayobject.php