There is really no “one true way” of this. Therefore, I will take it as a guide as to where you should go.
All information is based on this array.
$array = array( 1 => 'First', 2 => 'Second', 3 => 'Third', 4 => 'Fourth', 5 => 'Fifth' );
Array_slice () parameter. You said that you think this option is too crowded, but it seems to me that it is the shortest in code.
foreach (array_slice($array, 1) as $key => $val) { echo $key . ' ' . $val . PHP_EOL; }
Doing this 1000 times takes 0.015888 seconds.
There are array functions that handle a pointer, for example ...
current() - Returns the current element in the array.end() - Set the internal pointer of the array to your last element.prev() - Rewind the internal pointer of the array.reset() - Set the internal array pointer to its first element.each() - Returns the current key and value pair from the array and advances the array cursor.
Note that each() function is deprecated from PHP 7.2 and will be removed in PHP 8.
These features give you the fastest solution, over 1000 iterations.
reset($array); while (next($array) !== FALSE) { echo key($array) . ' ' . current($array) . PHP_EOL; }
Performing this 1000 times takes 0.014807 seconds.
Set the variable option.
$first = FALSE; foreach ($array as $key => $val) { if ($first != TRUE) { $first = TRUE; continue; } echo $key . ' ' . $val . PHP_EOL; }
Doing this 1000 times takes 0.01635 seconds.
I rejected the array_shift parameters because it edits your array and you never said it was acceptable.
Mark tomlin
source share