newbie forgot what the & means

Am looking for the answer to this so I can read up again what, when and why? This part is what I am speaking about [php] &$book [/php]
[php]
foreach ( $books as &$book ) {
$book[“authorName”] = $authors[$book[“authorId”]];
}
[/php]

Thanks

It creates a reference to the array value instead of copying it into a variable. This means that changes to the $book variable will be preserved in the $books array.

As PHP only pass references when working with objects this is the default behaviour when doing OOP.

ex:[php]<?php

echo ‘

’;

$json = ‘[{“key”: “value1”},{“key”: “value2”},{“key”: “value3”}]’;
$array = json_decode($json, true);
$obj = json_decode($json);

foreach ($array as $a) {
$a[‘key’] .= ’ :)’;
}
print_r($array);

foreach ($obj as $o) {
$o->key .= ’ :)’;
}
print_r($obj);

foreach ($array as &$a) {
$a[‘key’] .= ’ :)’;
}
print_r($array);[/php]

Thank you. I now will look up references to a variable memory.

Sponsor our Newsletter | Privacy Policy | Terms of Service