Php if логическое or пример

Урок 5. Условный оператор if, логические операции и сравнение в PHP

Главное в действие данное оператора — это условие. if в переводе с английского значит если. Условие принимается в качестве аргумента (то что в скобках). В качестве условия может выступать логическое выражение или логическая переменная. Если проще, то смысл выражения будет такой:

if (условие) условие выполнено, делаем так 
>
else
условие не выполнено, делаем иначе
>

Надеюсь логика условной операции понятна. Теперь давайте рассмотрим пример.

 $a = 5; 
$b = 25;

// Теперь внимание! Условие: Если $b больше $a
// Знаки > и < , как и в математике, обозначают больше и меньше
if($b > $a)
// если условие выполнено, то выполняем это действие
echo "$b больше $a";
>
else
// если не выполнено, то это
echo "$a больше или равно $b";
>
?>

Демонстрация Скачать исходники
В итоге скрипт выведет 25 больше 5. Пример довольно прост. Надеюсь всё понятно. Теперь предлагаю рассмотреть ситуацию сложнее, где нужно соблюсти несколько условий. Каждое новое условие будет содержать после основного условия if() — вспомогательное, которое записывается как else if(). В конце как обычно будет else.

Задача: В школе проводят тестирование. Скрипту нужно высчитать балл, зная условия получения каждой оценки и сам балл школьника. Давайте посмотрим как это записать, и не забудьте прочитать комментарий.

 $test = 82; // допустим школьник написал тест на 82 балла 

// первое условие напишем для пятёрки
if($test > 90)
// если условие соблюдено, то выполняем это действие.
echo "Оценка 5";
>
// Знак && обозначает "и, объединение", что условие соблюдено если и то, и то верно
// то есть балл меньше 91 и больше 80, тогда 4. Иначе условия считываются дальше
else if ($test < 91 && $test >80)
echo "Оценка 4";
>
else if ($test < 81 && $test >70)
echo "Оценка 3";
>
else
echo "Надо бы ещё раз написать тест. ";
>
?>

Демонстрация Скачать исходники
Наш школьник, который успевает и отдохнуть, и написать нормально тест получает оценку 4! А принцип работы надеюсь понятен.

Возможна и короткая запись работы условной операции, когда Вам нужно действие только в случае соблюдения условия.

$age = 19; // переменная с возрастом 

if ($age > 17) echo "Всё! Мне можно делать всё что угодно! Мне уже $age!";
>

Вполне себе милый пример короткой записи условной операции. else писать не обязательно.

Дальше встаёт другой вопрос: а есть же, наверное, какие-либо другие операторы сравнения?

Операторы сравнения в PHP

Принцип работы условной операции понятен. Но, как Вы понимаете, способов сравнить намного больше. Давайте посмотрим ниже на таблицу с операторами сравнения.

Пример Название Результат 
$a == $b Равно True, если $a равно $b
$a === $b Идентично True, если $a равно $b и обе переменных принадлежат одному типу
$a != $b Не равно True, если $a не равно $b
$a === $b Не идентично True, если $a не равно $b и оба их типа не совпадают
$a > $b Больше чем True, если $a больше, чем $b
$a < $b Меньше чем True, если $a меньше, чем $b
$a >= $b Больше или равно True, если $a больше или равно $b
$a

Теперь рассмотрим операторы на примерах:

$a = 5; 

// вопреки привычке = значит присваивание значение переменной, а == как равно
if ($a == 5) echo "$a равно 5"; // выведет "5 равно 5"
> else echo "$a не равно 5";
>

if ($a != 6) echo "$a не равно 6"; // выведет "5 не равно 6". Нужно в случае отрицания
> else echo "$a каким-то образом равно 6";
>

// с больше и меньше думаю всё понятно. Поэтому пример сложнее
if ($a <= 6)echo "$a меньше или равно 6"; // выведет "5 меньше или равно 6"
> else echo "$a больше 6";
>

Логические операторы PHP

Бывают случаи, когда нужно сравнить не одну переменную, а сразу две и более в одном условии. Для этого существуют логические операторы.

Пример Название Результат 
$a and $b Логическое 'и' TRUE если и $a, и $b TRUE.
$a or $b Логическое 'или' TRUE если или $a, или $b TRUE.
$a xor $b Исключающее 'или' TRUE если $a, или $b TRUE, но не оба.
! $a Отрицание TRUE если $a не TRUE.
$a && $b Логическое 'и' TRUE если и $a, и $b TRUE.
$a || $b Логическое 'или' TRUE если или $a, или $b TRUE.

Уже обратили внимание, что для операций и и или есть дополнительные операторы? Так сделано для того, чтобы расставить приоритеты в сложных операциях сравнения. В таблице логические операторы приведены в порядке приоритета: от меньшего к большему, то есть, например, || имеет больший приоритет, чем or.

Переходим к примерам

$a = 5; 
$b = 6;
$c = 7;

// условие: Если 5 не равно 6 (ВЕРНО) И 6 не равно 7 (ВЕРНО)
if ($a < 6 && $b != $c)echo "Действительно так!"; // выведет "Действительно так!" т.к. ОБА условия ВЕРНЫ
> else echo "Одно из условий не верно";
>

// условие: Если 6 не равно 6 (НЕВЕРНО) ИЛИ 6 не равно 7 (ВЕРНО)
if ($b != 6 || $b != $c) echo "Всё так!"; // выведет "Всё так!", т.к. хотя бы ОДНО из условий ВЕРНО
> else echo "Оба условия не верны";
>

Тернарный оператор

К вопросу тернарного кода я предлагаю Вам вернуться позже. Вовсе не упомянуть его я не мог, так как это важная конструкция, которая существенно сокращает размер кода. Предлагаю сразу рассмотреть код.

Суть кода: (условие) ? значение a если true : значение a если false

Таким образом, мы сокращаем запись оператора if. Однако, данная операция действительна только с присваиванием значений переменной. Теперь давайте рассмотрим готовый пример.

 // Пример использования тернарного оператора 
$settings = (empty($_POST['settings'])) ? 'По умолчанию' : $_POST['settings'];

// Приведенный выше код аналогичен следующему блоку с использованием if/else
if (empty($_POST['settings'])) $settings = 'По умолчанию'; // Если ничего не передано, то оставляем "По умолчанию"
> else $settings = $_POST['settings']; // Если передано, то $settings присваивается переданное значение.
>
?>

Прочитайте комментарии к коду и всё должно быть понятно.

Источник

Php if логическое or пример

worth reading for people learning about php and programming: (adding extras to get highlighted code)

about the following example in this page manual:
Example#1 Logical operators illustrated

.
// "||" has a greater precedence than "or"
$e = false || true ; // $e will be assigned to (false || true) which is true
$f = false or true ; // $f will be assigned to false
var_dump ( $e , $f );

// "&&" has a greater precedence than "and"
$g = true && false ; // $g will be assigned to (true && false) which is false
$h = true and false ; // $h will be assigned to true
var_dump ( $g , $h );
?>
_______________________________________________end of my quote.

If necessary, I wanted to give further explanation on this and say that when we write:
$f = false or true; // $f will be assigned to false
the explanation:

"||" has a greater precedence than "or"

its true. But a more acurate one would be

"||" has greater precedence than "or" and than "=", whereas "or" doesnt have greater precedence than " default">$f = false or true ;

If you find it hard to remember operators precedence you can always use parenthesys - "(" and ")". And even if you get to learn it remember that being a good programmer is not showing you can do code with fewer words. The point of being a good programmer is writting code that is easy to understand (comment your code when necessary!), easy to maintain and with high efficiency, among other things.

Evaluation of logical expressions is stopped as soon as the result is known.
If you don't want this, you can replace the and-operator by min() and the or-operator by max().

c ( a ( false ) and b ( true ) ); // Output: Expression false.
c ( min ( a ( false ), b ( true ) ) ); // Output: Expression is false.

c ( a ( true ) or b ( true ) ); // Output: Expression true.
c ( max ( a ( true ), b ( true ) ) ); // Output: Expression is true.
?>

This way, values aren't automaticaly converted to boolean like it would be done when using and or or. Therefore, if you aren't sure the values are already boolean, you have to convert them 'by hand':

c ( min ( (bool) a ( false ), (bool) b ( true ) ) );
?>

This works similar to javascripts short-curcuit assignments and setting defaults. (e.g. var a = getParm() || 'a default';)

( $a = $_GET [ 'var' ]) || ( $a = 'a default' );

?>

$a gets assigned $_GET['var'] if there's anything in it or it will fallback to 'a default'
Parentheses are required, otherwise you'll end up with $a being a boolean.

> > your_function () or return "whatever" ;
> ?>

doesn't work because return is not an expression, it's a statement. if return was a function it'd work fine. :/

This has been mentioned before, but just in case you missed it:

//If you're trying to gat 'Jack' from:
$jack = false or 'Jack' ;

// Try:
$jack = false or $jack = 'Jack' ;

//The other option is:
$jack = false ? false : 'Jack' ;
?>

$test = true and false; ---> $test === true
$test = (true and false); ---> $test === false
$test = true && false; ---> $test === false

NOTE: this is due to the first line actually being

due to "&&" having a higher precedence than "=" while "and" has a lower one

If you want to use the '||' operator to set a default value, like this:

$a = $fruit || 'apple' ; //if $fruit evaluates to FALSE, then $a will be set to TRUE (because (bool)'apple' == TRUE)
?>

instead, you have to use the '?:' operator:

$a = ( $fruit ? $fruit : 'apple' ); //if $fruit evaluates to FALSE, then $a will be set to 'apple'
?>

But $fruit will be evaluated twice, which is not desirable. For example fruit() will be called twice:
function fruit ( $confirm ) if( $confirm )
return 'banana' ;
>
$a = ( fruit ( 1 ) ? fruit ( 1 ) : 'apple' ); //fruit() will be called twice!
?>

But since «since PHP 5.3, it is possible to leave out the middle part of the ternary operator» (http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary), now you can code like this:

$a = ( $fruit ? : 'apple' ); //this will evaluate $fruit only once, and if it evaluates to FALSE, then $a will be set to 'apple'
?>

But remember that a non-empty string '0' evaluates to FALSE!

$fruit = '1' ;
$a = ( $fruit ? : 'apple' ); //this line will set $a to '1'
$fruit = '0' ;
$a = ( $fruit ? : 'apple' ); //this line will set $a to 'apple', not '0'!
?>

To assign default value in variable assignation, the simpliest solution to me is:

$v = my_function () or $v = "default" ;
?>

It works because, first, $v is assigned the return value from my_function(), then this value is evaluated as a part of a logical operation:
* if the left side is false, null, 0, or an empty string, the right side must be evaluated and, again, because 'or' has low precedence, $v is assigned the string "default"
* if the left side is none of the previously mentioned values, the logical operation ends and $v keeps the return value from my_function()

This is almost the same as the solution from [phpnet at zc dot webhop dot net], except that his solution (parenthesis and double pipe) doesn't take advantage of the "or" low precedence.

NOTE: "" (the empty string) is evaluated as a FALSE logical operand, so make sure that the empty string is not an acceptable value from my_function(). If you need to consider the empty string as an acceptable return value, you must go the classical "if" way.

In PHP, the || operator only ever returns a boolean. For a chainable assignment operator, use the ?: "Elvis" operator.

JavaScript:
let a = false;
let b = false;
let c = true;
let d = false;
let e = a || b || c || d;
// e === c

$a = false ;
$b = false ;
$c = true ;
$d = false ;
$e = $a ?: $b ?: $c ?: $d ;
// $e === $c
?>

Credit to @egst and others for the insight. This is merely a rewording for (formerly) lost JavaScript devs like myself.

$res |= true ;
var_dump ( $res );
?>

does not/no longer returns a boolean (php 5.6) instead it returns int 0 or 1

Источник

PHP If Statement with OR Operator

In this PHP tutorial, you will learn how to use OR operator in If-statement condition, and some example scenarios.

PHP If OR

PHP If condition can be compound condition. So, we can join multiple simple conditions with logical OR operator and use it as condition for PHP If statement.

If statement with OR operator in the condition

The typical usage of an If-statement with OR logical operator is

if ( condition_1 || condition_2 ) < //if-block statement(s) >
  • condition_1 and condition_2 can be simple conditional expressions or compound conditional expressions.
  • || is the logical OR operator in PHP. It takes two operands: condition_1 and condition_2 .

Since we are using OR operator to combine the condition, PHP executes if-block if at least one of the condition_1 or condition_2 is true. If both the conditions are false, then PHP does not execute if-block statement(s).

Examples

1. Check if a is 2 or b is 5.

In this example, we will write an if statement with compound condition. The compound condition contains two simple conditions and these are joined by OR logical operator.

PHP Program

PHP If OR

2. Check if given string starts with “a” or “b”.

In this example we use OR operator to join two conditions. The first condition is that the string should start with "a" and the second condition is that the string should start with "b" .

PHP Program

Second example of PHP If OR

Conclusion

In this PHP Tutorial, we learned how to write PHP If statement with AND logical operator.

Источник

Читайте также:  SSI
Оцените статью