I am trying to write a “smart” array search function that would remember the last found item.
function &GetShop(&$shops, $id) {
static $lastShop = null;
if ($lastShop == null) {
echo "lastShop is null <br/>";
} else {
echo "lastShop: [" . print_r($lastShop, true) . "]<br/>";
}
if ($lastShop != null && $lastShop['id'] == $id) {
return $lastShop;
}
for ($i = 0; $i < count($shops); $i++) {
if ($shops[$i]['id'] == $id) {
$lastShop = &$shops[$i];
return $shops[$i];
}
}
}
$shops = array(
array("id"=>"1", "name"=>"bakery"),
array("id"=>"2", "name"=>"flowers")
);
GetShop($shops, 1);
GetShop($shops, 1);
GetShop($shops, 2);
GetShop($shops, 2);
However, there seems to be an issuer with the line:
$lastShop = &$shops[$i];
When I run this function as it is, I get this output:
lastShop is null
lastShop is null
lastShop is null
lastShop is null
When I remove the “&” to pass by value instead, it works fine:
lastShop is null
lastShop: [Array ( [id] => 1 [name] => bakery ) ]
lastShop: [Array ( [id] => 1 [name] => bakery ) ]
lastShop: [Array ( [id] => 2 [name] => flowers ) ]
I would however like to pass by reference because the found array needs to be modified afterwards. Has somebody encountered this issue before and could advice how he solved it?
You are assigningNULLto$lastShopat the beginning of the function block on each call. Thus it is always reset toNULL.I found it in the documentation:
http://php.net/manual/en/language.variables.scope.php#language.variables.scope.references