Forum Moderators: coopster

Message Too Old, No Replies

PHP 7.x shorthand

         

csdude55

7:42 pm on Jul 21, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm now familiar with ? and <=>, and I've been using the ternary shorthand for awhile, but are there other nifty shorthands introduced in PHP 7 that I should know about?

Right now I'm specifically trying to find a way to shorten this:

if ($_COOKIE['whatever'] == 'foo' || $_COOKIE['whatever'] == 'bar') { ... }

I was hoping that this would work, but it doesn't; it always returns true because 'bar' is true:

if ($_COOKIE['whatever'] == 'foo' || 'bar') { ... }

But I'd definitely be interested in other shorthand code that I might not know :-)

Dimitri

8:58 pm on Jul 21, 2020 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member Top Contributors Of The Month



"Null coalescing operator"

For example, instead of doing:

$var = isset ( $something ) ? $something : false


You can do

$var = $something ?? false;


In both examples, if the variable $something exists, $var will take its value, otherwise, it will take the boolean false (or anything else).

$var = $something ?? 10;


$var takes the value of 10 if $something does not exist (or the value of $something, if it exists).

This can be very useful, when working with arrays, while testing if an index exists.

$var = $some_array[5] ?? 10;


$var = $some_array['price'] ?? 0;


Another example:

$var = $_GET['sometthing'] ?? false;


$var takes the value of the URL parameter 'something' if it exists, otherwise it takes the boolean false.

It can be chained

$var = $_GET['sometthing'] ?? $_POST['something'] ?? false;


check if the parameter 'something' is passed using get, if not check the post data.

Not PHP 7.x specific, but you also have array manipulation operator.

$my_array[]=80;

This adds the value 80 at the end of the array. You can also add a string, boolean, or even an array of-course.

In my opinion, these are the two most useful shorthand in PHP.