There are a couple ways to deal with it, e.g. you could unset the first element in the array and then iterate over it, but you could also apply a function that yields all but the first parameter and pass the array as parameters:
$num = ["20", "40", "89", "300", "190", "15"];
$new = 0;
$dropFirst = static fn ($_, string ...$a) => yield from $a;
foreach ($dropFirst(...$num) as $val) {
$new = $val;
echo "Value: $new\n";
}
I'd say it depends on the context what the needs are in the moment to foreach over $variable.
The $dropFirst above is a quick, hands-on Iterator (in form of the Generator subtype) and can be easily replaced with other, more verbose things.
E.g. you can wrap the array in an ArrayIterator and then use the LimitIterator:
$num = ["20", "40", "89", "300", "190", "15"];
$iterator = new LimitIterator(
new ArrayIterator($num),
1
);
$new = 0;
foreach ($iterator as $val) {
$new = $val;
echo "Value: $new\n";
}
This is certainly more lines of code, but you can separate limiting the iteration from the point where it's done (the foreach), still passing only a variable around (also known as inversion of control).
In the opposite you can put the control as well into the foreach body and just skip the first element. For example with a simple index check:
$num = ["20", "40", "89", "300", "190", "15"];
$new = 0;
foreach ($num as $index => $val) {
if (0 === $index) {
continue;
}
$new = $val;
echo "Value: $new\n";
}
So even all of these examples are working - as well as the ones in the other answers - you still have to think about where in your case you want to place control:
- change the original data (redefine)
- change what is
foreach'ed over (represent)
- change the
foreach body (present)