Adjacency list with array data I came through a question on Stack Overflow, which shows this array structure:

array (size=4)
  0 =&gt; 
    array (size=3)
      'id' =&gt; int 1
      'name' =&gt; string 'Anniversary' (length=11)
      'parent' =&gt; int 0
  1 =&gt; 
    array (size=3)
      'id' =&gt; int 12
      'name' =&gt; string 'New arrives' (length=11)
      'parent' =&gt; int 1
  2 =&gt; 
    array (size=3)
      'id' =&gt; int 13
      'name' =&gt; string 'Discount' (length=8)
      'parent' =&gt; int 12
  3 =&gt; 
    array (size=3)
      'id' =&gt; int 6
      'name' =&gt; string 'Birthday' (length=8)
      'parent' =&gt; int 0


and the required outcome needs to be the path for that list like shown below, implementation of adjacency list:




13 - Anniversary-&gt;New arrives-&gt;Discount
12 - Anniversary-&gt;New arrives
1 - Anniversary
6 - Birthday



I came to this solution:



$in = [
    ['id'=&gt;1, 'name'=&gt;'Anniversary', 'parent'=&gt;0],
    ['id'=&gt;12, 'name'=&gt;'New arrives', 'parent'=&gt;1],
    ['id'=&gt;13, 'name'=&gt;'Discount', 'parent'=&gt;12 ],
    ['id'=&gt;6, 'name'=&gt;'Birthday', 'parent'=&gt;0 ]
];  

function path($element, $input) {
    $return = $input[ array_search($element, array_column($input, 'id')) ];
    $str [] = $return ['name'];
    if($return ['parent'] != 0) {
        $str [] = path($return ['parent'], $input);
    }
    return implode('-&gt;', array_reverse($str));
}

var_dump(path(13,$in));


It gets the task done, but I want to know if any improvements can be made to optimize the approach to the problem.
Your code is really good, so there's not much to improve on, that I can see, but nonetheless:



You shouldn't have whitespace before, or inside your brackets unless required:


   $return = $input[ array_search($element, array_column($input, 'id')) ];
                    ^                                                  ^
   $str [] = $return ['name'];
       ^            ^
   if($return ['parent'] != 0) {
             ^
       $str [] = path($return ['parent'], $input);
           ^                 ^



All these lines above have unnecessary whitespace, however the line below is missing whitespace after the comma in path().


var_dump(path(13,$in));
                 ^





You really ought not to name your variables $return or $str, because the first is a system keyword, and the second is undescriptive &amp; possibly confusing as it's really an array, not a string.



The implode string -&gt; could also be -&gt; with an extra space, or even a unicode long (or not long) rightwards arrow: ⟶, along with the extra space, visually output would be more readable, and better looking.

13 - Anniversary -&gt; New arrives -&gt; Discount // With added space
13 - Anniversary ⟶ New arrives ⟶ Discount // With added space and long rightwards arrow