each()
has been officially deprecated in PHP 7.2 but it is out of fashion since PHP 4 (i.e. since about 20 years ago).
It returns an array containing at position 0 the key and at position 1 the value of the current element of the array passed to it as argument and advances the internal array pointer to the next element. Its behaviour can be confusing, this is why foreach()
(or another way to iterate over the array) is preferred to be used instead.
Your code:
reset($units);
list($unit, ) = each($units);
reset($units)
moves the internal pointer of the $units
array to its first element. Then each($units)
returns the key and the value of the first element (and advances to the next element but this is not important for the rest of the code).
list($unit, )
copies in $unit
the first value from the array (of two values) returned by each($units)
and ignores the second value.
All in all, the code above puts in $unit
the key of the first element of the array (the first key of the array).
There are several ways to achieve the same result without each()
.
One of them is to use array_keys()
to get all the keys then get the first of them using the usual array indexing with [0]
:
$unit = array_keys($units)[0];
Or you can use reset()
to move the internal array pointer to its first element then key()
to get the key of the current element.
reset($units);
$unit = key($units);
However I do not recommend relying on the internal pointer of the array. It works fine but the code that uses it can easily introduce hidden bugs.
Since PHP 7.3 you can use the function array_key_first()
that produces the same result as the code above but it is faster:
$unit = array_key_first($units);