Few most useful features of PHP 7.4

PHP is a server-side language that started with a procedural approach and later in updates brought the OOPs approach. But in today’s article, we will talk about the launch of PHP version 7.4 and Few most useful features of PHP 7.4.

Lets see a quick list of few most useful features first.

  1. Arrow functions
  2. Type declarations
  3. Null coalescing assignment operator
  4. Unpacking inside arrays
  5. Array merge functions without arguments

So that was a quick list, now let’s see them individually with some explanation, that will make more clear to you.

Arrow functions

If you have written javascript then you have already used or seen arrow function. So here PHP brings arrow functions, basically, arrow function in PHP is a mixture of anonymous function and closure. Let’s see example of how an arrow function looks.

$y = 1;
$x = 4;
$fn1 = fn() => $x + $y;
echo $fn1(); //call function 

//output
5

Type declarations

As a PHP developer we know PHP automatically cast variable data type based on the value. But even though for better practice and understanding now you can use data type in PHP also. Lets see an example how it looks with data type.

//before
$id = 1 // integer

//from 7.4 can also be used with data type

class User {
    public int $id;
    public string $name;
}

Null coalescing assignment operator (??=)

With this feature PHP 7.4 saved your 3 lines of code, it’s not a lot but still, its better than writing full if condition, and if the variable is null then we assign some value to it. Well, this can be done in one line.

$array['key'] ??= 'hello';

// is equivalent to

if (!isset($array['key'])) {
    $array['key'] = 'hello';
}

Unpacking inside arrays

Another feature that has been seen in javascript and iI personally use in this feature a lot in javascript. It’s nice to see PHP is making up with other languages. In javascript, this feature called spread operator and that exactly unpacks the data inside array or object. The very same thing is happening in PHP also, It’s like merging arrays in one array. Let’s see an example to make it more clear.

$middleNos = ['three', 'four'];
$numbers = ['one', 'two', ...$middleNos, 'five'];
// ['one', 'two', 'three', 'four', 'five'];

Array merge functions without arguments

Once in a while, you must have used array_merge() function to merge two or more arrays. Now you whats new in this, so this could be useful when you are using spread operator as a parameter in array_merge() and even if your parameter is null, It won’t return an error. It will simply return an empty array.

So that was all about a few most useful features of PHP 7.4 according to me. Let me know what you think about it if I have missed something, leave a comment in the below comment box.

You can read more feature on PHP’s official website.

See also

Leave a Reply

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