Php if and or combined

Использование AND / OR в if else заявление PHP

Как вы используете «AND / OR» в инструкции if else else? Будет ли это:

if ($status = 'clear' AND $pRent == 0)
if ($status = 'clear' OR $pRent == 0)
  • Многие программисты предпочитают && и || вместо and и / or , но они работают одинаково (безопасно для приоритета).
  • $status = ‘clear’ должен быть $status == ‘clear’ . = is присваивание, == это сравнение.

Немного поздно, но не важно …
вопрос: «Как вы используете …?» короткий ответ: вы делаете это правильно

Другой вопрос: «Когда вы его используете?»
Я использую && вместо AND и || вместо OR .

в этом случае результат «ЛОЖЬ», потому что B не 1, теперь что, если

Это вернет «TRUE», даже если B все еще не является значением, которое мы запрашиваем, есть еще один способ вернуть TRUE без использования OR / || и это будет XOR

в этом случае нам нужна только одна из наших переменных, но НЕ ОБА, если оба из них TRUE, результат будет FALSE.

  1. используйте == для сравнения. Вы использовали = который предназначен для назначения.
  2. используйте && для «и» и || для «или». and or будут работать, но они нетрадиционные.

В ответах здесь есть некоторые шуточные и вводящие в заблуждение комментарии, даже частично некорректная информация. Я хотел бы попытаться улучшить их:

Во-первых , как указывали некоторые, у вас есть ошибка в коде, относящаяся к вопросу:

if ($status = 'clear' AND $pRent == 0) 

должен быть (обратите внимание на == вместо = в первой части):

if ($status == 'clear' AND $pRent == 0) 

которая в этом случае функционально эквивалентна

if ($status == 'clear' && $pRent == 0) 

Во-вторых , заметим, что эти операторы ( and or && || ) являются операторами короткого замыкания. Это означает, что если ответ можно определить с уверенностью из первого выражения, второй никогда не будет оценен. Опять же это не имеет значения для вашей отлаженной строки выше, но это чрезвычайно важно, когда вы комбинируете эти операторы с заданиями, потому что

В-третьих , реальная разница между and or и && || является их приоритетом для операторов . В частности, важно, чтобы && || имеют более высокий приоритет, чем операторы присваивания ( = += -= *= **= /= .= %= &= |= ^= >= ), хотя and or имеют меньшую точность, чем операторы присваивания. Таким образом, в заявлении, которое сочетает использование присваивания и логической оценки, важно, какой из них вы выберете.

Модифицированные примеры из страницы PHP на логических операциях :

будет оценивать значение true и присваивать это значение $e , потому что || имеет более высокий приоритет оператора, чем = , и поэтому он, по существу, оценивает следующее:

присваивает false значение $e (а затем выполняет операцию or операцию и оценивает значение true ), поскольку = имеет более высокий приоритет оператора, чем or , по существу, оценивая следующим образом:

Тот факт, что эта двусмысленность даже существует, позволяет многим программистам всегда использовать && || и тогда все работает ясно, как можно было бы ожидать на языке, таком как C, т.е. сначала логические операции, затем назначение.

Читайте также:  Ide среда разработки html

Некоторые языки, такие как Perl, используют такую ​​конструкцию часто в формате, подобном этому:

$connection = database_connect($parameters) or die("Unable to connect to DB."); 

Это теоретически назначало бы подключение к базе данных к $connection , или если это не сработало (и мы предполагаем, что здесь функция вернет то, что в этом случае вернется к false ), это приведет к завершению скрипта сообщением об ошибке. Из-за короткого замыкания, если соединение с базой данных завершается успешно, die() никогда не оценивается.

Некоторые языки, которые допускают эту конструкцию прямо запрещают присвоения в условных / логических операциях (например, Python), чтобы устранить неоднозначность в обратном порядке.

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

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

$e = (false || true); $e = (false or true); 

Вооружившись всеми этими знаниями, я предпочитаю использовать and or потому, что чувствую, что он делает код более удобочитаемым. У меня просто есть правило не комбинировать назначения с логическими оценками. Но в этот момент это просто предпочтение, и последовательность важна здесь намного больше, чем какая-то сторона, которую вы выберете.

AND и OR являются просто синтаксическим сахаром для && и || , как в JavaScript, или в других языках синтаксиса языка C.

Он появляется AND и OR имеют более низкий приоритет, чем их эквиваленты стиля С.

if ($status = 'clear' && $pRent == 0)
if ($status = 'clear' || $pRent == 0)

Я думаю, что у меня немного путаницы здесь. 🙂 Но, похоже, никто другой не имеет ..

Вы спрашиваете, какой из них следует использовать в этом сценарии? Если да, то И это правильный ответ .

Если вы спрашиваете о том, как работают операторы,

В php и AND, && и OR, || будет работать одинаково. Если вы новичок в программировании, а php – один из ваших первых языков, я предлагаю использовать AND и OR, потому что он повышает читаемость и уменьшает путаницу при проверке. Но если вы уже знакомы с любыми другими языками, то вы, возможно, уже знакомы с && и || операторы.

ive заменил «else» на «&&», поэтому оба они размещены … argh

«И» не работает в моем PHP-коде.

Источник

Php if and or combined

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’!
?>

Читайте также:  Прочитать строку до разделителя python

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.

Источник

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