Php switch break return

‘break’ from a switch, then ‘continue’ in a loop

Amazing, I never knew this, took me ages to realise this was the problem, that a switch’s break will affect the outter foreach : (from php site) » Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2. «

3 Answers 3

After clarification, looks like you want continue 2;

If I was to use «break 2;» would it not continue to execute code after the $numbers loop, but still inside the $letters loop?

Instead of break , use continue 2 .

The program will go back to the beginning of the numbers loop. This is unique to php. You can view this here =>php.net/manual/en/control-structures.switch.php

» Note: Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2. «

I know this is a serious necro but. as I arrived here from Google figured I’d save others the confusion.

If he meant breaking out from the switch and just ending the number’s loop, then break 2; would’ve been fine. continue 2; would just continue the number’s loop and keep iterating through it just to be continue ‘d each time.

Читайте также:  Php json форматирование вывода

Ergo, the correct answer ought to be continue 3; .

Going by a comment in the docs continue basically goes to the end of the structure, for switch that’s that (will feel the same as break), for loops it’d pick up on the next iteration.

"; $numbers= array(1,2,3,4,5,6,7,8,9,0); $letters = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'); $i = 0; foreach($letters as $letter) < ++$i; echo $letter . PHP_EOL; foreach($numbers as $number) < ++$i; switch($letter) < case 'd': // So here I want to 'break;' out of the switch, 'break;' out of the // $numbers loop, and then 'continue;' in the $letters loop. continue 3; // go to the end of this switch, numbers loop iteration, letters loop iteration break; case 'f': continue 2; // skip to the end of the switch control AND the current iteration of the number's loop, but still process the letter's loop break; case 'h': // would be more appropriate to break the number's loop break 2; >// Still in the number's loop echo " $number "; > // Stuff that should be done if the 'letter' is not 'd'. echo " $i " . PHP_EOL; > 
Hello, World! a 1 2 3 4 5 6 7 8 9 0 11 b 1 2 3 4 5 6 7 8 9 0 22 c 1 2 3 4 5 6 7 8 9 0 33 d e 1 2 3 4 5 6 7 8 9 0 46 f 57 g 1 2 3 4 5 6 7 8 9 0 68 h 70 i 1 2 3 4 5 6 7 8 9 0 81 

continue 2; not only processes the letter’s loop for the letter d but even processes the rest of the number’s loop (note that $i is both incremented and printed after f). (Which may or may not be desirable. )

Hope that helps anyone else that winds up here first.

Источник

The PHP switch statement

This post is part of a series of posts about the fundamentals of PHP.

In the previous article we discussed the if statement, where it said you can have many different elseif statements if you wanted to handle many different scenarios, but it gets to a point where you should consider swapping to a switch statement.

$myVar = 'green'; if ($myVar === 'red')  echo 'It is red'; > elseif ($myVar === 'blue')  echo 'It is blue'; > elseif ($myVar === 'green')  echo 'It is green'; > 

This can be rewritten using a switch statement. Each condition you want to match has a case where you pass in the variable you want to match. Within the case, you put the code you want to run if the condition matches. Then you need to add a break, otherwise the code will continue to check for matches in the rest of the switch statement.

$myVar = 'green'; switch ($myVar)  case 'red': echo 'It is red'; break; case 'blue': echo 'It is blue'; break; case 'green': echo 'It is green'; break; > 

Default case

A very useful feature of the switch statement is allowing a default if none of the other cases match. Sometimes you don’t know what the variable will be and it allows you to catch this edge case. You could even use it to throw an exception to deliberately stop any further code running.

$myVar = 'orange'; switch ($myVar)  case 'red': echo 'It is red'; break; case 'blue': echo 'It is blue'; break; case 'green': echo 'It is green'; break; default: throw new Exception('It is not a matching colour'); > // Fatal error: Uncaught Exception: It is not a matching colour 

Multiple case matching

Sometimes you want to do the same thing for multiple matching cases. If you were to use an if statement you would need to either repeat the code multiple times or use an or ( || ) in your condition.

$myVar = 'green'; if ($myVar === 'red' || $myVar === 'green')  echo 'It is red or green'; > 

In a switch statement you can do this easily by listing multiple cases one after the other, then adding your code to run with a break after;

$myVar = 'green'; switch ($myVar)  case 'red': case 'green': echo 'It is red or green'; break; case 'blue': echo 'It is blue'; break; > 

Returning from a switch case

Sometimes you don’t need a break in a switch statement. This is when you directly return from the switch statement. The example below has a switch statement in a function, returning the result from the matching case.

function findTheColour($colour)  switch ($colour)  case 'red': return 'It is red'; case 'blue': return 'It is blue'; case 'green': return 'It is green'; default: return 'It does not match'; > > echo findTheColour('green'); // It is green 

I know that some developers (such as me) think it looks strange not having the breaks in a switch statement as it’s nice to break up the code.

Alternative syntax

As with an if statement, you can also use colons instead of brackets and end the switch with endswitch.

switch ($myVar): case 'red': echo 'It is red'; break; case 'blue': echo 'It is blue'; break; case 'green': echo 'It is green'; break; endswitch; 

You can also use semicolons instead of colons after the case if you wanted to.

Using an Array instead

Some people don’t like using switch statements as they can seem a bit verbose. There is a potential alternative using an array to provide the options if it is a simple scenario.

$colours = [ 'red' => 'It is red', 'green' => 'It is green', 'blue' => 'It is blue', ]; $myVar = 'green'; echo $colours[$myVar]; //It is green 

The above will work fine for red, green or blue, but if it is an unknown colour, such as orange, then you will end up with an undefined index error.

You could use a null coalescing operator (PHP 7.0 onwards) to catch this error and return a default response.

echo $colours[$myVar] ?? 'It does not match'; 

Match

PHP 8.0 has introduced the match statement. It offers shorter syntax and it returns a value. There is a great article about the differences between match and switch on stitcher.io by Brent.

Источник

PHP: Конструкция Switch

Многие языки в дополнение к условной конструкции if включают в себя switch. В этом уроке мы познакомимся с ним.

Это специализированная версия if, созданная для некоторых особых ситуаций. Например, ее имеет смысл использовать там, где есть цепочка if else с проверками на равенство. Например:

 elseif ($status === 'paid') < // Делаем два >elseif ($status === 'new') < // Делаем три >else < // Делаем четыре >

Эта составная проверка обладает одной отличительной чертой, каждая ветка здесь, это проверка значения переменной status . Switch позволяет записать этот код короче и выразительнее:

Свитч довольно сложная конструкция с точки зрения количества элементов из которых она состоит:

  • Внешнее описание, в которое входит ключевое слово switch . Переменная, по значениям которой switch будет выбирать поведение. И фигурные скобки для вариантов выбора.
  • Конструкции case и default , внутри которых описывается поведение для разных значений рассматриваемой переменной. Каждый case соответствует if в примере выше. default это особая ситуация, соответствующая ветке else в условных конструкциях. Как и else , указывать default не обязательно.
  • break нужен для предотвращения «проваливания». Если его не указать, то после выполнения нужного case выполнение перейдет к следующему case и так либо до ближайшего break , либо до конца switch.

Фигурные скобки в switch не определяют блок кода как это было в других местах. Внутри допустим только тот синтаксис, который показан выше. То есть там можно использовать case или default . А вот внутри каждого case (и default ) ситуация другая. Здесь можно выполнять любой произвольный код:

Иногда результат, полученный внутри case — это конец выполнения функции, содержащей switch. В таком случае его нужно как-то вернуть наружу. Для решения этой задачи есть два способа.

Первый способ — создать переменную перед switch, заполнить ее в case и затем, в конце, вернуть значение этой переменной наружу:

Второй способ проще и короче. Вместо создания переменной, case позволяет внутри себя делать обычный возврат из функции. После return никакой код не выполняется, поэтому мы можем избавиться от break :

Switch хоть и встречается в коде, но технически всегда можно обойтись без него. Ключевая польза при его использовании в том, что он лучше выражает намерение программиста, когда нужно проверять конкретные значения переменной. Хотя кода и стало физически больше, читать его легче, чем блоки с elseif.

Задание

Реализуйте функцию getNumberExplanation() , которая принимает на вход число и возвращает объяснение этого числа. Если для числа нет объяснения, то возвращается just a number . Объяснения есть только для следующих чисел:

Если вы зашли в тупик, то самое время задать вопрос в «Обсуждениях». Как правильно задать вопрос:

  • Обязательно приложите вывод тестов, без него практически невозможно понять что не так, даже если вы покажете свой код. Программисты плохо исполняют код в голове, но по полученной ошибке почти всегда понятно, куда смотреть.

Тесты устроены таким образом, что они проверяют решение разными способами и на разных данных. Часто решение работает с одними входными данными, но не работает с другими. Чтобы разобраться с этим моментом, изучите вкладку «Тесты» и внимательно посмотрите на вывод ошибок, в котором есть подсказки.

Это нормально 🙆, в программировании одну задачу можно выполнить множеством способов. Если ваш код прошел проверку, то он соответствует условиям задачи.

В редких случаях бывает, что решение подогнано под тесты, но это видно сразу.

Создавать обучающие материалы, понятные для всех без исключения, довольно сложно. Мы очень стараемся, но всегда есть что улучшать. Если вы встретили материал, который вам непонятен, опишите проблему в «Обсуждениях». Идеально, если вы сформулируете непонятные моменты в виде вопросов. Обычно нам нужно несколько дней для внесения правок.

Кстати, вы тоже можете участвовать в улучшении курсов: внизу есть ссылка на исходный код уроков, который можно править прямо из браузера.

Источник

Оцените статью