PHP Arrow Function and Ternary Operator

Created At: 2022-06-25 22:16:13 Updated At: 2022-06-25 22:31:27

Latest PHP verions have included some cool features like arrow function and ternary operator. 

They are favourite and with them you would write less code and be more productive.

Arrow function

Look at a simple function

<?php

function add($a, $b)
{
	return $a + $b;
}
echo add(4, 5);

With PHP arrow function this function could be accomplished in line

<?php

$add = fn ($a, $b) => $a + $b;

echo $add(4, 5);

If you notice the above code, you will see that, if you want to use PHP arrow function then you need to use fn keyword for it.

Let's take a look at another example

<?php

$greeting = 'Welcome to Educative, master '; 
$greet = fn ($username) => $greeting . $username; // arrow function

echo "arrow function: ", $greet('John')  . "\n";

Ternary operator

This is another cool feature. This feature is also implemented in other languages like Dart and GoLang.

Let's take a look an example

<?php
$age = 18;
if($age>18){
 echo "You are an adult";
}else{
 echo "You are not an adult";
}

With ternary operator the above condition becomes one line

<?php
$age = 18;
echo $age>18 ? "You are an adult":"You are not an adult";

This is cool right !

Comment

Add Reviews