PHP

PHP 8 – New Features

PHP 8 released late last year but I never got round to taking a look. I tend to run LTS versions of Ubuntu which are a little behind the cutting edge versions of these things. It’s a big update but I pulled out 3 things I found of interest.

str_contains()

It’s simply a way to check if a string contains a sub string. Seems odd that it’s taken this long to get this function as something like it has been available in other languages for ages. (Python’s has the ‘in‘ operator and Javascript has ‘includes‘).

Previously in PHP if we wanted to see if the string ‘Quick brown fox’ contained the word ‘fox’ we’d have to do the following:

if (strpos('Quick brown fox', 'fox') !== false) { 
   /* Do something */ 
}

Whilst it worked it wasn’t particularly nice to read. Now we can do:

if (str_contains('Quick brown fox', 'fox')) { 
   /* Do something */ 
}

Syntactic sugar maybe but it helps readability which is never a bad thing.

It’s worth mentioning quickly there are another two new methods which are similar:

str_starts_with('Quick brown fox', 'Quick'); // true
str_ends_with('Quick brown fox', 'fox'); // true

Match Expression

Match expressions are a control structure and can be thought of as a grown up version of switch statements. The operate in a similar way but don’t require break statements and allow multiple matches on a single line. For example consider this example of working out which continent a country belongs to:

$country = 'India';

switch ($country) {
    case 'Belgium':
    case 'France':
    case 'Germany':
        $continent = 'Europe';
        break;
    case 'China':
    case 'India':
    case 'Japan':
        $continent = 'Asia';
        break;
    case 'Kenya':
    case 'South Africa':
    case 'Tanzania':
        $continent = 'Africa';
        break;
    default:
        $continent = 'Unknown';
        break;
}

echo $continent;

Using the Match expression you could show the above as:

$country = 'India';

$continent = match ($country) {
    'Belgium', 'France', 'Germany' => 'Europe',
    'China', 'India', 'Japan' => 'Asia',
    'Kenya', 'South Africa', 'Tanzania' => 'Africa',
    default => 'Unknown',
};

echo $continent;

I think that’s much more succinct and easier to read.

The nullsafe operator

You may be familia with the Null coalescing operator introduced in PHP 7. It was added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). For example:

$name = $_GET['name'] ?? 'John Doe';

// Was equivalent to

$username = isset($_GET['name']) ? $_GET['name'] : 'John Doe';

The only problem with this is that it didn’t work with method calls so quite frequently you’d have to do something like this:

$country = $booking->getCountry();

$countryName = $country ? $country->getName() : null;

The new nullsafe operator allows you to reduce this to one line:

$countryName = $booking->getCountry()?->getName();

How neat is that?