Array_shift() syntax explanation

I am trying to follow the logic in a code snippet I found on google.
$user = array_shift( &array: $result);

Intelephense is giving me an error on the & and the :

if I remove the &array: then ibreak other unrelated lines in the code.

Can some explain the use of The &array: in that sentence. I understand and have used the array_shift() function before but I havenever seen the this usage before.

Thank you in advance for any help.

Lindhum2.0

Well, it means a pointer to the variable. Usually, inside functions, the variable is passed and inside the function, a copy is used during the lifespan of the function. So…

function Ernie($var1, $var2) {
$var1 = 0;
return $var1;
}

This would always return zero, but, NEVER EVER touch the orginal $var1’s values.
But, this version:

function Ernie(&var1, $var2) {
$var1 = 0;
return $var1;
}

Would set the original variable “$var1” to zero and it will be altered by this function. In most cases, it is not used often as it is hard to follow the logic of the entire function process. Here is what the description actually says for this type of process:

The & operator tells PHP not to copy the array when passing it to the function. Instead, a reference to the array is passed into the function, thus the function modifies the original array instead of a copy.
( Basically what I just said… )

The code snippet you found is wrong. The correct syntax is:

$user = array_shift($result);

array_shift accepts a reference to an array. That’s normally represented by &array in the function declaration, but this syntax isn’t required when calling the function.

This call will have two effects:

  1. The variable $user will be set to the first value in $result.
  2. The first value in $result will be removed.

Note the second effect happens to a variable outside the function scope; this is where references are useful.

For example:

$result = ['adam', 'becky', 'charlie'];
$user = array_shift($result);

At the end of this code:

  1. $user will be equal to 'adam'
  2. $result will be equal to ['becky', 'charlie']

The other problems you see when you remove the &array: are unrelated. PHP is showing you the first error it finds, which is this one; when you fix it you’re not causing another error, PHP is just showing you the next error.

Thank you for the quick reply and confirming what I thought.

Sponsor our Newsletter | Privacy Policy | Terms of Service