Here are the most useful PHP 8 new features

PHP8 is out, now what would I tell you more? when and how they released it ? come on, I know you’re not here for that kind of information.
if you’re a regular and lazy php developer like me then you’d be interested to learn about PHP 8 key new features only, which means updates that applies mostly to your regular daily coding and not those updates that you’re going to learn about now then forget forever because, as an ordinary server side developer, you rarely come across a scenario where they might be needed.

Now what’s a PHP 8 key update for me? it’s anything that can save us if only a second on something we do very often, like for example the way we write loops, pass parameters to a function, how we manipulate arrays…etc.
One second here and one second there and you end up spending less time on repetitive syntaxes and focus more on what’s more important.
Also, a key feature is something that is now allowing you to do what you were not able to in the older version (PHP 7 or older).

I’ll try to give an example of a common scenario for each PHP 8 new feature I present. You can get a real understanding of how useful an update could be for you by looking at the examples.

let’s now leave introductions aside and explore each one of the most useful PHP 8 new features.

1.Trailing Comma in functions Parameter List

commas are so annoying when you manipulate function parameters. Especially when we pass a lot of parameters into a single function.
for example, sometimes you need to move the last parameter to a different position:

Not only you need to add a comma after positioning the parameter, but also you need to remove the last one in order to get a correct syntax, otherwise you’ll get the error:

					

Parse error: syntax error, unexpected ‘)’ in C:\wamp\www\straightdev\index.php on line 11

but with php 8, leaving the trailing comma is no more a problem. You can now leave a comma after the last parameter like this:

insertUser($firstName,)

so now, moving parameters becomes more practical and doesn’t require any extra step like adding or removing a comma

2.Named parameters

I wished this new php 8 feature existed before now, it would have saved me a lot of time. What are named parameters? it’s simply a more organised way to pass parameters to a function. This is very useful when declaring too many parameters, especially when you use optional parameters. Here’s a scenario where you would benefit of such a feature:

function insertUser($firstName, $lastName, $gender, $email, $pass,  $country , $city , $dateOfBirth ){
     //insert user into database
}

As you can see, the function insertUser contains 8 parameters. The problem when using too many parameters is that it’s hard to remember their order at the moment when you call the function, so you end up losing time trying to recall the position of each one, but you generally end up revisiting the function declaration before being able to format your function call correctly. Without mentioning that it’s always hard to read and understand a function call when it contains too many parameters

insertUser("straight", "developer", 0, "admin@straightdev.com", "*******",  "algeria" , "annaba" , "1991-01-01" );

Thanks to the php 8 named parameters new feature. Not only you’re no more obliged to respect the order of the parameters, but your function is now way more readable ! This feature allow you to name each one of your parameters when you pass them, here’s how:

insertUser(
          firstName: "straight",
          lastName: "developer",
          gender: 0,
          email: "admin@straightdev.com",
          pass: "*******",  
          country: "algeria" , 
          city: "annaba" , 
          dateOfBirth: "1991-01-01" ,
);

Reading this portion of code is easy isn’t it? imagine the impact this new way of writing function calls can have on your code !
you can now position your parameters the way you want, php 8 will assign the values according to their names

insertUser(
          email: "admin@straightdev.com",
          firstName: "straight",
          dateOfBirth: "1991-01-01", 
          lastName: "developer",
          gender: 0, 
          country: "algeria" , 
          city: "annaba" , 
          pass: "*******", 
);

But this feature is mostly useful when you use optional parameters. Let me show an example so you can better understand what I am saying, let’s suppose we declared this function:

function insertBook($authorId, $title, $price, $pages = false, $lang = false, $editor = false, $year = false ){
     //insert book into database
}

As you can see our function insertBook() contains 4 optional parameters. They’re optionals because they’re not always available to us therefore we might sometimes pass false or just skip the parameters rather than passing a real value.
The problem when you use too many optional parameters is that sometimes, you just can’t skip writing the default value for optional parameters. To illustrate this, let’s suppose that we want to insert a book and that we only have its author, title, price and year.
the function call will look like:

insertBook(123, "Les misérables", 20, false, false, false, 1862 )

As you can see $pages, $lang and $editor might be optionals yet we had to pass false in order to be able to reach the $year position and pass a value there. There’s clearly something wrong about this way of writing parameters especially if you deal with functions that have a high number of optional parameters. PHP 8 new named parameters feature solves the problem :

insertBook(
          authorId: 123,
          title: "Les misérables",
          price: 20, 
          year: 1862,
);

The most interesting part with the new named parameters feature is that you can still combine between the traditional and the new way of passing parameters. By doing that, you can avoid repetition as much as you can. Ideal when you’re a lazy developer and you want to use this feature only when it’s really needed, example:

insertBook(123,"Les misérables",20, year: 1862);

3.The match expression

The best way to understand the match expression is to compare it to switch. See it like a nicer and shorter way to return a specific value based on different conditions. Let’s take a common switch statement as an example and write its equivalence with match:

switch ($extension) {
            case 'jpg':
                $fileType="image";
                break;
            case 'flv':
                $fileType="video";
                break;
            
            default:
               $fileType="unknown";
                break;
        }

Our switch statement determines the type of a file based on its extension, simple. Now, let’s try reproducing the same thing using match

  $fileType = match ($extension) {
            'jpg' => 'image',
            'flv' => 'video',
            default => 'unknown',
        }

The first thing to notice is that match takes way less space than switch. It is easier to read and memorize. I know many beginners who tend to avoid using switch just because they find it hard to use its syntax but I think that with match no one will ever complain. As you can see, match does not require a break statement and it automatically returns a value ! But that’s not all, match offers a better approach to handle multiple matching conditions. For example, let’s say we wanted to cover more image extensions in our previous example. First let’s try doing this with switch:

switch ($extension) {
            case 'jpg':
            case 'jpeg':
            case 'png':
                $fileType="image";
                break;
            case 'flv':
                $fileType="video";
                break;
            
            default:
               $fileType="unknown";
                break;
        }

If you’re not familiar with this syntax, writing cascading case keys just like we did is how you combine multiple conditions into one matching block using the switch statement. Now, here’s how you do the same using match:

  $fileType = match ($extension) {
            "jpg" , "jpeg" , "png" => "image",
            "flv" => "video",
            default => "unknown",
        }

simple enough isn’t it? you can combine all your matching conditions using nothing but a comma.
At the end, match is a nice alternative to switch but not all the time. match has its own limitations too. For example, match doesn’t allow more than one expression per condition unlike switch , so keep note of this before you start thinking that you’re no more in need of it.

4.the str_contains function

have you ever asked yourself why there had never been a proper php function to detect if a string contains a substring? just like javascript:

str.includes("world");

so you won’t have to do this ugly thing in PHP:

strpos($str, "world") !== false; 

Since it’s better late than never, one of PHP 8 new features is a function that checks if a string contains a substring or not, this is how you use the php 8 new str_contains function:

str_contains($str, 'world');

I think that there’s nothing I can clarify more. The first parameter is the haystack and the second one is the needle. The function returns true only if the needle is in the haystack otherwise it returns false.

I think I mentioned the most useful PHP 8 new features for me. There are too many other updates you might like to know about. You can read about them here.
I am sure the other features are interesting too. But They don’t have as much impact on a regular php developer’s life as the ones I mentioned. If you think that there’s any other php 8 new feature that has a potential of doing a big impact on how ordinary php developers write php then let me know in the comments and explain how.

Also read...

Leave a Reply

Your email address will not be published. Required fields are marked *