PHP offers several shorthand syntax to make code more concise, simple and readable.
- Ternary Operator
- Null Coalescing Operator
- Null Coalescing Assignment Operator
- Short Echo Tag
- Spaceship Operator
- Short-Hand Control Structures
A simplest way to write conditional expressions with ternary operator.
Syntax:
$result = $condition ? $value_if_true : $value_if_false;
Example:
$price = 2500;
$offerInPercentage = ($price >= 2000) ? 20 : 10;
echo $offerInPercentage; // Output: 20
Null coalescing operator is ??
. Which is used to easiest way to assign a default value to a variable if it is a null.
Syntax:
$value = $variable ?? 'default_value';
Example:
$name = $_SESSION['user_name'] ?? 'Guest';
echo "Welcome, $name!";
It is denoted as ??=
symbols. This is used to assigns a value to a variable only if it is not already set.
Syntax:
$variable ??= 'default_value';
Example:
$name = isset($_POST['user_name']) ? $_POST['user_name'] : null;
$name ??= 'Guest';
echo "Welcome, $name!";
A shorter way to echo a variable in PHP. This is not always supported by default. But it need to enable in PHP configuration.
Syntax:
<?= $variable; ?>
Example:
<?= 'Hello, world!' ?>
It is denoted as <=>
symbols. It compares two values and returns -1, 0, or 1. If a first value is less than a second value, then it will return -1. If both values are equal, then it will return 0. If a first value is greater than a second value, then it will return 1.
Syntax:
$result = $a <=> $b;
Example:
$a = 10;
$b = 5;
$comparison = $a <=> $b;
echo $comparison; // Output: 1
- Conditional Statements:
// if
if ($condition):
// code to be executed if condition is true
endif;
// if-else
if ($condition):
// code to be executed if condition is true
else:
// code to be executed if condition is false
endif;
- Loops:
// while
while ($condition):
// code to be executed until condition is true
endwhile;
// do-while
do:
// code to be executed first even condition is false
while ($condition);
// for
for ($i = 0; $i < 10; $i++):
// code to be executed until condition is true
endfor;
// foreach
foreach ($array as $value):
// Iterates through $array elements
endforeach;
- Switch statement:
// switch
switch ($variable):
case 'value1':
// code to be executed if matches this case
break;
case 'value2':
// code to be executed if matches this case
break;
default:
// code to be executed if none of the case matches
endswitch;