We want to add a new element to the $cpa array in each call to the function. To do this we need always to add to the original empty array. The ampersand allows us to to this. Without it, a copy of the array would be passed to the function and we would just keep adding to a new empty array each time. &$cpa passes the array by reference (ie its address in memory) instead of a copy.
P.S.
This method below (which stores all the category data into a $cat_data array instead of running a query in every call to the function, is 5x faster. $cat_data looks like this...
Array
(
[532] => Array
(
[name] => Motorbikes::1
[parent] => 0
)
[533] => Array
(
[name] => Cars::2
[parent] => 0
)
[534] => Array
(
[name] => Boats::3
[parent] => 0
)
[535] => Array
(
[name] => Bicycles::4
[parent] => 0
)
.
.
.
)
CODE
$cat_data = [];
$res = $pdo->query("SELECT id
, CONCAT(name, '::', position) as name
, parent
FROM category
");
foreach ($res as $r) {
$cat_data[$r['id']] = [ 'name' => $r['name'], 'parent' => $r['parent'] ] ;
}
$category_path_array = [];
retrieve_category_path ($cat_data, 552, $category_path_array);
$breadcrumbs = join('/', $category_path_array);
echo $breadcrumbs;
function retrieve_category_path (&$cats, $id, &$cpa)
{
array_unshift($cpa,$cats[$id]['name']);
if ($cats[$id]['parent']) {
retrieve_category_path($cats, $cats[$id]['parent'], $cpa);
}
}
Thank you - much appreciated.