Php and with no shortcuts

the new code

To receive more information, including news, updates, and tips, follow me on Twitter or add me on Google+.

This site helps millions of visitors while remaining ad-free. For less than the price of a cup of coffee, you can help pay for bandwidth and server costs while encouraging further articles.

projects

A Sass color keyword system for designers. Replaces CSS defaults with improved hues and more memorable, relevant color names.

An auto-generated #RWD image slider. 3.8K of JS, no JQuery. Drop in images, add a line of CSS. Done.

Massive Head Canon. Intelligent discussion of movies, books, games, and technology.

books

Useful PHP Syntax Shortcuts

As a general rule, code is like writing: the more concise it is, the better. Fewer characters tend to mean lower errors, and fewer bugs. To this end, there are a few syntax shortcuts that are very useful.

if shortcut – no braces

If your if statement has only one directive, like the following:

if-else shortcut

You’re probably used to the long, formal version of the if-else statement in PHP:

While there is nothing wrong with this statement, it’s more efficient to use the shortened version, using the ternary operator:

echo shortcut

echo has a shortcut too, so long as the shortcut for the PHP tag itself is supported on the server. This is particularly useful if you are echoing out small snippets as variables. So rather than:

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.

Источник

Php and with no shortcuts

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 AND Operator

Summary: in this tutorial, you’ll learn about the PHP AND operator and how to use it to build a complex logical expression.

Introduction to the PHP AND operator

The logical AND operator accepts two operands and returns true if both operands are true ; otherwise, it returns false .

PHP uses the and keyword to represent the logical AND operator:

expression1 and expression2

The following table illustrates the result of the and operator:

expression1 expression2 expression1 and expression2
true true true
true false false
false true false
false false false

Since PHP keywords are case-insensitive, the AND and and operators are the same:

expression1 AND expression2

By convention, you should use the and operator in the lowercase format.

In addition to using the and keyword, PHP uses && as the logical AND operator:

The && and and operators return the same result. The only difference between the && and and operators are their precedences.

The and operator has higher precedence than the && operator. The precedence of an operator specifies the order in which PHP evaluates.

PHP AND operator examples

Suppose that you want to offer discounts to customers who buy more than three items with a price of more than 99. To determine whether customers can get a discount or not, you can use the AND operator as follows:

 $price = 100; $qty = 5; $discounted = $qty > 3 && $price > 99; var_dump($discounted); Code language: HTML, XML (xml)
bool(true)Code language: JavaScript (javascript)

If you change the $qty to 2 , the $discounted will be false like this:

 $price = 100; $qty = 2; $discounted = $qty > 3 && $price > 99; var_dump($discounted);Code language: HTML, XML (xml)

In practice, you’ll use the logical AND operator in the if, if-else, if-elseif, while, and do-while statements.

Short-circuiting

When the value of the first operand is false , the logical AND operator knows that the result must be also false . In this case, it doesn’t evaluate the second operand. This process is called short-circuiting.

See the following example:

 $debug = false; $debug && print('PHP and operator demo!'); Code language: HTML, XML (xml)
  • First, define the variable $debug and initialize it to false .
  • Second, use the logical AND operator to combine the $debug and print() . Since $debug is false , PHP doesn’t evaluate the call to the print() function.

If you change the $debug to true , you’ll see a message in the output:

 $debug = true; $debug && print('PHP and operator demo!');Code language: HTML, XML (xml)
PHP and operator demo!Code language: plaintext (plaintext)

Summary

  • Use the PHP AND operator ( and , && ) to combine two boolean expressions and returns true if both expressions evaluate to true; otherwise, it returns false .
  • The logical AND operator is short-circuiting.

Источник

Php and with no shortcuts

There are two string operators. The first is the concatenation operator (‘.’), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator (‘ .= ‘), which appends the argument on the right side to the argument on the left side. Please read Assignment Operators for more information.

$a = «Hello » ;
$b = $a . «World!» ; // now $b contains «Hello World!»

$a = «Hello » ;
$a .= «World!» ; // now $a contains «Hello World!»
?>

See Also

User Contributed Notes 6 notes

As for me, curly braces serve good substitution for concatenation, and they are quicker to type and code looks cleaner. Remember to use double quotes (» «) as their content is parced by php, because in single quotes (‘ ‘) you’ll get litaral name of variable provided:

// This works:
echo «qwe < $a >rty» ; // qwe12345rty, using braces
echo «qwe» . $a . «rty» ; // qwe12345rty, concatenation used

// Does not work:
echo ‘qwerty’ ; // qwerty, single quotes are not parsed
echo «qwe $arty » ; // qwe, because $a became $arty, which is undefined

A word of caution — the dot operator has the same precedence as + and -, which can yield unexpected results.

The above will print out «3» instead of «Result: 6», since first the string «Result3» is created and this is then added to 3 yielding 3, non-empty non-numeric strings being converted to 0.

To print «Result: 6», use parantheses to alter precedence:

» < $str1 >< $str2 > < $str3 >» ; // one concat = fast
$str1 . $str2 . $str3 ; // two concats = slow
?>
Use double quotes to concat more than two strings instead of multiple ‘.’ operators. PHP is forced to re-concatenate with every ‘.’ operator.

If you attempt to add numbers with a concatenation operator, your result will be the result of those numbers as strings.

echo «thr» . «ee» ; //prints the string «three»
echo «twe» . «lve» ; //prints the string «twelve»
echo 1 . 2 ; //prints the string «12»
echo 1.2 ; //prints the number 1.2
echo 1 + 2 ; //prints the number 3

Some bitwise operators (the and, or, xor and not operators: & | ^ ~ ) also work with strings too since PHP4, so you don’t have to loop through strings and do chr(ord($s[i])) like things.

See the documentation of the bitwise operators: https://www.php.net/operators.bitwise

Be careful so that you don’t type «.» instead of «;» at the end of a line.

It took me more than 30 minutes to debug a long script because of something like this:

The output is «axbc», because of the dot on the first line.

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