Skip to content

Latest commit

 

History

History
152 lines (126 loc) · 3.25 KB

short-hand-syntax.md

File metadata and controls

152 lines (126 loc) · 3.25 KB

➲ Short-Hand Syntax:

PHP offers several shorthand syntax to make code more concise, simple and readable.

☴ Overview:

  1. Ternary Operator
  2. Null Coalescing Operator
  3. Null Coalescing Assignment Operator
  4. Short Echo Tag
  5. Spaceship Operator
  6. Short-Hand Control Structures

✦ Ternary Operator:

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:

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!";

✦ Null Coalescing Assignment Operator:

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!";

✦ Short Echo Tag:

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!' ?>

✦ Spaceship Operator:

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

✦ Short-Hand Control Structures:

  • 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;

⇪ To Top

❮ Previous TopicNext Topic ❯

⌂ Goto Home Page