Array start at 1?

I have one single part of my app where if my arrays could start at index 1 it would be great.

Is there some way to do something like

foreach ($array as ($index + 1) => $val) { }

or to somehow put a setting to make it start at index 1?


foreach ($array as $index => $val) {
    // skip first
    if ($index == 0) {
        continue;
    }
   // code here
 }

you could also just remove the first element with unset($array[0])

unless you dont actually want to skip the first element, but you just want the key to be 1 instead of 0?

Nope, not skip it… just have 1-based index on the array… It’s multidimensional, so I’d rather have some function or setting to change it, rather than adding an $realIndex = $index + 1 on each foreach

How are you setting up the array in the first place? If you explicitly declare the first index of an array, the rest of your keys will follow that number. Here’s an example:

$myarr[50] = 'test'; // $myarr[50] equal to "test"
$myarr[]   = 'foo';  // $myarr[51] equal to "foo"
$myarr[]   = 'bar';  // $myarr[52] equal to "bar"

there is no such setting.


foreach ($array as $foo => $val) {
     $index = $foo + 1;
}

you could also use a for() loop but the concept is the same, you need to manually start a variable at 1 and increment it, or you need to add 1 to the current key.

alright… figured there was no alternative way but I thought I’d ask anyways :slight_smile:

thanks