Logical Operators & Strings
In this lesson we will look at how to use logical operators and strings in PHP.
Logical Operators
Use of the ||
“or” comparison operator is discouraged, as its clarity on some output devices is low (looking like the number 11, for instance). &&
is preferred over AND but either are acceptable, and space should always precede and follow !
.
Example: Incorrect
Press + to interact
if ($foo || $bar)if ($foo AND $bar) // okay but not recommended for common syntax highlighting applicationsif (!$foo)if (! is_array($foo))
Example: Correct
Press + to interact
if ($foo OR $bar)if ($foo && $bar) // recommendedif ( ! $foo)if ( ! is_array($foo))
Strings
Always use single quoted strings unless you need variables parsed, and in cases where you do need variables parsed, use braces to prevent greedy token parsing. You may also use double-quoted strings if the string contains single quotes, so you do not have to use escape characters.
Example: Incorrect
Press + to interact
"My String" // no variable parsing, so no use for double quotes"My string $foo" // needs braces'SELECT foo FROM bar WHERE baz = \'bag\'' // ugly
Example: Correct
Press + to interact
'My String'"My string {$foo}""SELECT foo FROM bar WHERE baz = 'bag'"