Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start foreach loop on associative array at the second element

Tags:

php

I have associative array such as:

$myArray = array(
  'key1' => 'val 1',
  'key2' => 'val 2'
  ...
);

I do not know the key values up front but want to start looping from the second element. In the example above, that would be from key2 onwards.

I tried

foreach(next(myArray) as $el) {

}

but that didnt work.

Alternatives may be array_slice but that seems messy. Am i missing something obvious?

like image 518
Marty Wallace Avatar asked Sep 08 '13 20:09

Marty Wallace


1 Answers

There really is no "one true way" of doing this. So I'll take it as a benchmark 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'
);

The array_slice() option. You said you thought this option was overkill, but it seems to me to be the shortest on code.

foreach (array_slice($array, 1) as $key => $val)
{
    echo $key . ' ' . $val . PHP_EOL;
}

Doing this 1000 times takes 0.015888 seconds.


There is the array functions that handle the pointer, such as ...

  • current() - Return the current element in an array.
  • end() - Set the internal pointer of an array to its last element.
  • prev() - Rewind the internal array pointer.
  • reset() - Set the internal pointer of an array to its first element.
  • each() - Return the current key and value pair from an array and advance the array cursor.

Please note that the each() function has been deprecated as of PHP 7.2, and will be removed in PHP 8.

These functions give you the fastest solution possible, over 1000 iterations.

reset($array);
while (next($array) !== FALSE)
{
    echo key($array) . ' ' . current($array) . PHP_EOL;
}

Doing this 1000 times, takes 0.014807 seconds.


Set a 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 options because it edits your array and you've never said that was acceptable.

like image 131
Mark Tomlin Avatar answered Sep 22 '22 08:09

Mark Tomlin