Логические операторы в PHP
Логические операторы позволяют указывать сразу несколько условий для одного блока IF:
Оператор && , который ещё называется логическое И, приводит значения слева и справа к булеву типу, а затем и сам возвращает булево значение: true если слева и справа true , либо false если одно из условий false .
Другими словами, если и одно, и другое условие истинно, то и оператор && возвращает истину. Что и отражает название оператора.
Оператор || или логическое ИЛИ возвращает истину когда истинно хотя бы одно из двух условий:
5 || 1 > 2) echo 'Условие выполнено.'; ?>
В коде выше команда echo будет выполнена, поскольку одно из условий истинно.
Все логические операторы в PHP
$a && $b | Истина, если $a и $b равны true. |
$a || $b | Истина, если хотя бы одна из $a и $b равна true. |
$a xor $b | Истина, если одна из $a и $b равна true, но не обе. |
!$a | Истина, если $a не равна true. |
$a and $b | Аналогично && |
$a or $b | Аналогично || |
Между операторами && и and , а также между || и or есть небольшое различие — порядок выполнения.
Как вы знаете, умножение имеет больший приоритет, чем сложение. Так вот, операторы and и or имеют приоритет ниже, чем оператор присваивания = . Результат можно увидеть в следующем примере:
Поскольку у = приоритет выше, PHP воспримет код так:
Т.е. сначала он присваивает переменной $var значение true , а затем происходит операция true and false , которая не имеет смысла, поскольку не влияет на значение переменной.
Ниже расположена таблица с приоритетами операторов. С некоторыми из них вы уже встречались. Чем выше оператор в таблице — тем выше его приоритет.
- ++ — ~ (int) (float) (string) (array) (object) (bool) @
- * / %
- + — .
- < >=
- == != === !== <>
- &&
- ||
- ? : (тернарный оператор)
- = += -= *= **= /= .= %= &= |= ^= <>=
- and
- xor
- or
Теперь мы можем определить, что приоритет операторов сравнения (==, != и т.д.) выше, чем у логических операторов. Эта информация пригодится нам для выполнения задачи.
Задача
Каким будет результат выполнения следующего выражения?
Php примеры логические операторы
worth reading for people learning about php and programming: (adding extras to get highlighted code)
?php>
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. :/?php
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
PHP: логические операторы и операторы сравнения
Переменная типа boolean (логический тип данных) может принимать всего два значения: TRUE (истина) или FALSE (ложь). Логическую переменную можно получить двумя путями: либо напрямую присвоить одно из двух значений, либо присвоить в неё результат выполнения логического оператора. Вот описание всех логических операторов:
Пример | Название | Результат |
---|---|---|
$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. |
Примеры логических операторов
Операторы сравнения
Операторы сравнения возвращают также как и логические операторы тип boolean и используются для того, чтобы сравнить две переменные:
Пример | Название | Результат |
---|---|---|
$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 | Меньше или равно | TRUE если $a меньше или равно $b. |
$a >= $b | Больше или равно | TRUE если $a больше или равно $b. |
Примеры операторов сравнения
Понравилась или помогла статья? Самое лучшее, что ты можешь сделать — это поделиться ею в любой из своих соцсетей (даже если ты поделишься в твиттере или google+, которыми ты не пользуешься — это очень поможет развитию моего блога). Спасибо! А если ты еще и оставишь любой комментарий снизу в обсуждениях, то это будет двойное СПАСИБО!
Ссылка на статью на всякий случай:
Крутов Герман © 2009-2023
krutovgerman2007@ya.ru
Я ВКонтате