PHP Snippet - Array By-Reference

Posted at




/**
* @param array $array by-reference
* @param string $key
* @param mixed $value
* @return mixed
*/
function set_and_return(&$array, $key, $value) {
$array[ $key ] = $value;

return $value;
}

$arr = array();
$arr['hello'] = "world";

echo "before:";
var_dump($arr);

set_and_return($arr, 'foo', 'bar');

echo "after:";
var_dump($arr);
?>



before:

array (size=1)
'hello' => string 'world' (length=5)
after:

array (size=2)
'hello' => string 'world' (length=5)
'foo' => string 'bar' (length=3)