简体   繁体   中英

php syntax - using 'or' and '&&' in statement

This is for a text field password input. Here is my code:

$vaar is what is entered into that field.

if(($vaar !='pass01' or 'pass02') && (!empty($vaar))) {

I can't figure out the correct syntax. I've tried || , or , xor . I've also tried placing 'pass01' and 'pass02' in their own ( ) 's.

What I want it to do is this:

If $vaar isn't 'pass01' or 'pass02' and $vaar is not empty then do this:

just a syntax error, but I can't figure it out!

You're looking for:

if( !empty($vaar) && ($vaar != 'pass01' && $vaar != 'pass02')) {

Note that I've put the empty() check first, which will short-circuit the evaluation should $vaar in fact be empty.

Edit: To better reflect the OP's wording (and logic), this is identical to the following, because of Demorgan's law. ):

if( !empty($vaar) && !($vaar == 'pass01' || $vaar == 'pass02')) {

Reads: If $vaar is not empty and $vaar is not pass01 or pass02

if(($vaar !== 'pass01' and $vaar !== 'pass02') and (!empty($vaar))) {
   // ...
}

Alternatively:

if(($vaar !== 'pass01' && $vaar !== 'pass02') && (!empty($vaar))) {
   // ...
}

What you actually mean is:

If $vaar is not equal to "pass01" AND $vaar is not equal to "pass02" AND $vaar is not empty, then ...

Note that I have kept your original parentheses in there, but since they are all AND, you may remove them, like this:

if(!empty($vaar) && $vaar !== 'pass01' && $vaar !== 'pass02') {
   // ...
}

Here, I have also moved the empty language construct to the beginning of the conditional, as if the variable is empty then the conditional will evaluate the false immediately, preventing an E_NOTICE error for Undefined variable $vaar if the variable is undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM