Reputation: 214
I want to skip the first entry of a foreach loop, I know a way to do it, but it uses a lot of lines of code, I was wondering if there was an easier way:
$i = 0;
foreach($url AS $u) {
if($i!=0) $cats[check_url($u)] = $u;
$i++;
}
Is there a better more official way?
Upvotes: 2
Views: 1050
Reputation: 4216
If you have numeric keys for $url
you can simply do like this :
foreach($url AS $k => $u) {
if($k) $cats[check_url($u)] = $u;
}
But if your array has non numeric keys, I think what you have is the best way to do!
Upvotes: 0
Reputation: 1139
Another possible approach would be to use PHP's built in array_shift() function to pop the first item off the array before looping through.
If you aren't sure how your $url array is indexed, simply removing index [0] with unset($url[0])
may or may not solve the problem. For example, if $url is indexed by association, it may look more like this:
$url['first'] = "a value";
$url['second'] = "some other value";
$url['third'] = "a different value";
To be certain you are excluding the first "indexed" element, regardless of the key associated with it, you can use array_shift() like so:
array_shift($url);
This pops off the first element and reset()s the array pointer.
After this you can carry out your foreach loop like normal.
Upvotes: 1