- БЛОГ ПРО WEB
- Рассказываю о web-разработке и помогаю создавать сайты
- Условный оператор PHP (if, else, elseif)
- Оператор эквивалентности PHP
- P.S.
- Php if else int
- User Contributed Notes 10 notes
- PHP if. else. elseif Statements
- PHP Conditional Statements
- PHP — The if Statement
- Syntax
- Example
- PHP — The if. else Statement
- Syntax
- Example
- PHP — The if. elseif. else Statement
- Syntax
- Example
- PHP — The switch Statement
- PHP if else elseif
- Syntax
- Example
- Output
- Syntax
- Example
- Output
БЛОГ ПРО WEB
Рассказываю о web-разработке
и помогаю создавать сайты
Условный оператор PHP (if, else, elseif)
Как и во многих языках программирования, в PHP есть условный оператор, который очень важен и помогает проверять различные условия, от чего зависит конечный результат вывода.
Допустим мы определили переменную $age
Задача: Пропишем условие, где переменная $age равна 18:
Начинается оператор с ключевого слова if, условие прописывается следом за словом if, в круглых скобках ( УСЛОВИЕ ) и результат вывода должен находиться следом в фигурных скобках
Обрати внимание, что сравнение происходит через двойной знак РАВНО. Выведем результат с помощью оператора ECHO
Сравнение может быть не только со знаком равно. Можно так же использовать
== — равно
— меньше чем
> — больше чем
— меньше или равно чем
>= — больше или равно чем
!= — НЕ равно
Например, если задача: вывести сообщение если возраст больше чем 18
Или, если задача: вывести сообщение если возраст больше ИЛИ РАВНО 18
Мы так же можем прописать сразу несколько условий для одного оператора IF, используя AND или OR
Например задача: Вывести сообщение если у возраст равен 18 и рост выше или равен 170
Понятно, нужно создать еще одну переменную $height (РОСТ)
Тоже самое можно писать так
Можно условие сделать еще сложнее используя круглые скобки внутри условия
= 170) || ($age > 18 && $height >= 170)) < echo 'Мне 18 лет и мой рост 170 см'; >?>
У оператора IF есть дополнительные операторы ELSE и ELSEIF
Например, выводим сообщение о том что мне 18 лет и сообщение в отрицательном случае, с оператором ELSE
Или выводим все варианты с помощью ELSEIF вот так
elseif ($age > 18) < echo 'Мне больше 18 лет'; >elseif ($age < 18) < echo 'Мне меньше 18 лет'; >?>
И сюда можем добавить так же ELSE
elseif ($age > 18) < echo 'Мне больше 18 лет'; >elseif ($age < 18) < echo 'Мне меньше 18 лет'; >else < echo 'Фиг знает сколько мне лет ;)'; >?>
Проверка на существование переменной. Часто приходится проверять существует ли определенная переменная или нет. В этом нам поможет функция isset()
И есть обратная функция, на проверку отсутствия переменной, empty()
В случае отсутствия переменной, без проверки, сервер нам выдаст ошибку при выводе несуществующей переменной.
В последних версиях PHP, условия могут прописываться еще таким образом, без использования фигурных скобок
Переменные в условии могут содержать не только числа, но и текст, строковая переменная должна содержать значение в кавычках
B условие будет прописано соответствующим образом (в кавычках)
Если у нас значение переменной — булевое (true, false), то проверка на значение, может быть такая
Оператор эквивалентности PHP
При использовании оператора if, есть некоторые тонкости, о которых, я думаю, нужно рассказать именно в этой статье. При сравнивании 2х значений, нужно учитывать и типы значений, потому что при сравнивании значений разных типов, может вывестись странный результат, к которому вы можете быть неготовы )
Результат будет РАВНО, хотя мы точно видим что 0 и ‘текст’ ну ни как не могут быть равны. PHP имеет свойство преобразовывать значения условий в число в том случае, если в условии есть хотя бы одно значение типа integer, в данном случае у нас $val1 является — integer. С точки pрения PHP условие у нас выглядит так
А при преобразовании текста в число (int)$val2, мы получим 0 и так как у нас $val1 тоже равен 0, мы сравниваем 2 числа 0 и 0, вот у нас и результат РАВНО
Значит, если мы хотим сравнить именно эти 2 значения, нам необходимо привести оба значения к одному типу, и лучше преобразовать в строку
Вот теперь PHP сравнит значения как текст ‘0’ и текст ‘text’ и результат будет НЕ РАВНО как и ожидалось. Или же есть другой способ — использовать Оператор эквивалентности PHP. Это значит что вместо сравнения в виде двойного равенства, мы можем использовать тройное равенство и проблема решится сама собой )
P.S.
Условный оператор IF является одним из самых важных операторов и одновременно является самым простым, но не смотря на его простоту, получилось много информации только об IF, и я уверен что, что-нибудь я упустил 😉
Php if else int
Often you’d want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what else is for. else extends an if statement to execute a statement in case the expression in the if statement evaluates to false . For example, the following code would display a is greater than b if $a is greater than $b , and a is NOT greater than b otherwise:
The else statement is only executed if the if expression evaluated to false , and if there were any elseif expressions — only if they evaluated to false as well (see elseif).
Note: Dangling else
In case of nested if — else statements, an else is always associated with the nearest if .
Despite the indentation (which does not matter for PHP), the else is associated with the if ($b) , so the example does not produce any output. While relying on this behavior is valid, it is recommended to avoid it by using curly braces to resolve potential ambiguities.
User Contributed Notes 10 notes
An alternative and very useful syntax is the following one:
statement ? execute if true : execute if false
Ths is very usefull for dynamic outout inside strings, for example:
print(‘$a is ‘ . ($a > $b ? ‘bigger than’ : ($a == $b ? ‘equal to’ : ‘smaler than’ )) . ‘ $b’);
This will print «$a is smaler than $b» is $b is bigger than $a, «$a is bigger than $b» if $a si bigger and «$a is equal to $b» if they are same.
If you’re coming from another language that does not have the «elseif» construct (e.g. C++), it’s important to recognise that «else if» is a nested language construct and «elseif» is a linear language construct; they may be compared in performance to a recursive loop as opposed to an iterative loop.
$limit = 1000 ;
for( $idx = 0 ; $idx < $limit ; $idx ++)
< $list []= "if(false) echo \" $idx ;\n\"; else" ; >
$list []= » echo \» $idx \n\»;» ;
$space = implode ( » » , $list );| // if . else if . else
$nospace = implode ( «» , $list ); // if . elseif . else
$start = array_sum ( explode ( » » , microtime ()));
eval( $space );
$end = array_sum ( explode ( » » , microtime ()));
echo $end — $start . » seconds\n» ;
$start = array_sum ( explode ( » » , microtime ()));
eval( $nospace );
$end = array_sum ( explode ( » » , microtime ()));
echo $end — $start . » seconds\n» ;
?>
This test should show that «elseif» executes in roughly two-thirds the time of «else if». (Increasing $limit will also eventually cause a parser stack overflow error, but the level where this happens is ridiculous in real world terms. Nobody normally nests if() blocks to more than a thousand levels unless they’re trying to break things, which is a whole different problem.)
There is still a need for «else if», as you may have additional code to be executed unconditionally at some rung of the ladder; an «else if» construction allows this unconditional code to be elegantly inserted before or after the entire rest of the process. Consider the following elseif() ladder:
PHP if. else. elseif Statements
Conditional statements are used to perform different actions based on different conditions.
PHP Conditional Statements
Very often when you write code, you want to perform different actions for different conditions. You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
- if statement — executes some code if one condition is true
- if. else statement — executes some code if a condition is true and another code if that condition is false
- if. elseif. else statement — executes different codes for more than two conditions
- switch statement — selects one of many blocks of code to be executed
PHP — The if Statement
The if statement executes some code if one condition is true.
Syntax
Example
Output «Have a good day!» if the current time (HOUR) is less than 20:
PHP — The if. else Statement
The if. else statement executes some code if a condition is true and another code if that condition is false.
Syntax
if (condition) code to be executed if condition is true;
> else code to be executed if condition is false;
>
Example
Output «Have a good day!» if the current time is less than 20, and «Have a good night!» otherwise:
if ($t < "20") echo "Have a good day!";
> else echo «Have a good night!»;
>
?>
PHP — The if. elseif. else Statement
The if. elseif. else statement executes different codes for more than two conditions.
Syntax
if (condition) code to be executed if this condition is true;
> elseif (condition) code to be executed if first condition is false and this condition is true;
> else code to be executed if all conditions are false;
>
Example
Output «Have a good morning!» if the current time is less than 10, and «Have a good day!» if the current time is less than 20. Otherwise it will output «Have a good night!»:
if ($t < "10") echo "Have a good morning!";
> elseif ($t < "20") echo "Have a good day!";
> else echo «Have a good night!»;
>
?>
PHP — The switch Statement
The switch statement will be explained in the next chapter.
PHP if else elseif
Conditional execution of one or more statements is a most important feature of any programming language. PHP provides this ability with its if, else and elseif statements. Primary usage of if statement is as follows −
Syntax
The expression in front of if keyword is a logical expression, evaluated either to TRUE or FALSE. If its value is TRUE, statement in next line is executed, otherwise it is ignored. If there are more than one statements to be executed when the expression is TRUE, statements are grouped by using additional pair of curly brackets,
If another staement or a group of statements are required to be executed when expression is FALSE, else keyword is used and one or more statements (inside another pair of curly brackets) are written below it
Following example shows typical use of if and else keywords. It also uses readline() function to read keyboard input in command line execution of following code. It receive marks as input and displays result as pass or fail depending on marks>=50 or not.
Example
=50)< echo "The result is pass" . "
"; echo "congratulations" . "
"; > else< echo "The result is Fail". "
"; echo "Better luck next time" . "
"; > ?>
Output
This will produce following result −
The result is Fail Better luck next time
Many a times, if a condition is false, you may require to check if another condition is fulfilled. In this case, another if statement has to be used in else clause of first if statement. There may be a series of cascaded if — else blocks which makes the program tedious. PHP provides elseif statement to address this problem.
As the keyword indicates, elseif is combination of if and else keywords. It works similar to else keyword, with a little difference. Conditional logic of the code has multiple if conditions. The program flow falls through cascade of elseif conditionals and first instance of elseif expression being true, its block is executed and the execution comes out. Last conditional block is a part of else clause, which will be executed only if all preceding if and elseif expressions are false
Syntax
if (expression) < statement; >elseif (expression) < statement; >elseif (expression) < statement; >. . else < statement; >>
In following example, elseif statement is used to calculate grade of student based on marks
Example
Output
This will produce following result −