0

I saw this function (Get all permutations of a PHP array?), but i can't understand on how some of these coding works, can help to explain? I am new in php by the way.
Here's the code:

function pc_permute($items, $perms = array()) 
    {
        if (empty($items))
        { 
            echo join(' ', $perms) . "<br />";
        } 
        else 
        {
            for ($i = count($items) - 1; $i >= 0; --$i) 
            {
                 $newitems = $items;
                 $newperms = $perms;
                 list($foo) = array_splice($newitems, $i, 1);
                 array_unshift($newperms, $foo);
                 pc_permute($newitems, $newperms);
             }
        }
    }
    $arr = array('peter', 'paul', 'mary');
    pc_permute($arr);

why uselist($foo)? I tried to use array, it doesn't work(I don't understand list)
And why use array_unshift($newperms, $foo);? for what? Sorry, I really new in php T.T

Community
  • 1
  • 1
Newbie
  • 1,584
  • 9
  • 33
  • 72

1 Answers1

0

List takes an array and place it in variable ,if the array size is 3 for example then in the list function you need to mention 3 variables.

list($foo) = array_splice($newitems, $i, 1);

What he have done is to take $i put it in $foo and remove it from the array. This could also look like this -

$foo = array_splice($newitems, $i, 1)[0];

But some will consider this code as harder to read.

Then the array_unshift($newperms, $foo) means take $foo and place it at the start of $newperms array. so if the array looked like

Array ( [0] => a [1] => b [2] => c )

and $foo equals d the array after running the function would look like this -

Array ( [0] => d [1] => a [2] => b [3] => c )
Gal Sisso
  • 1,939
  • 19
  • 20
  • so the variable `$foo` will only content 1 element each time? then why need to use list but not the normal variable? or can it modified to a simpler way? – Newbie Feb 21 '15 at 23:55
  • because `array_splice` return an array and you need to convert it into string. – Gal Sisso Feb 22 '15 at 08:39