Чтобы пропустить цикл foreach/loop в PHP, вы можете использовать оператор continue. Оператор continueпозволяет преждевременно завершить текущую итерацию цикла и перейти к следующей итерации. Вот пример:
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as $number) {
if ($number == 3) {
continue; // Skip the current iteration when the number is 3
}
echo $number . ' '; // Output the number
}
В этом примере, когда число равно 3, выполняется оператор continue, и цикл немедленно переходит к следующей итерации. В результате число 3 пропускается, и на выходе будет: 1 2 4 5.
Вот еще несколько методов, которые можно использовать для пропуска цикла foreach/loop в PHP:
-
Использование
array_filter():$numbers = [1, 2, 3, 4, 5]; $filteredNumbers = array_filter($numbers, function ($number) { return $number != 3; // Exclude the number 3 }); foreach ($filteredNumbers as $number) { echo $number . ' '; // Output the number } -
Использование цикла
for:$numbers = [1, 2, 3, 4, 5]; $count = count($numbers); for ($i = 0; $i < $count; $i++) { $number = $numbers[$i]; if ($number == 3) { continue; // Skip the current iteration when the number is 3 } echo $number . ' '; // Output the number } -
Использование
array_walk():$numbers = [1, 2, 3, 4, 5]; array_walk($numbers, function ($number) { if ($number == 3) { return; // Skip the current iteration when the number is 3 } echo $number . ' '; // Output the number });