Shorthand Operations in PHP
Let's take the following code:
<?php
$num = 1;
$num = $num + 2;
?>
As you can see, the variable is assigned
its current value plus something else. For
such operations, there is a special shorthand
operator +=, see the example:
<?php
$num = 1;
$num += 3; // equivalent to $num = $num + 3;
?>
There are similar operators for other mathematical operations:
<?php
$num = 2;
$num -= 3; // equivalent to $num = $num - 3;
?>
<?php
$num = 2;
$num *= 3; // equivalent to $num = $num * 3;
?>
<?php
$num = 2;
$num /= 3; // equivalent to $num = $num / 3;
?>
<?php
$str = 'a';
$str .= 'b'; // equivalent to $str = $str . 'b';
?>
Simplify the provided code using shorthand operations:
<?php
$num = 47;
$num = $num + 7;
$num = $num - 18;
$num = $num * 10;
$num = $num / 15;
echo $num;
?>
Simplify the provided code using shorthand operations:
<?php
$str = 'a';
$str = $str . 'b';
$str = $str . 'c';
echo $str;
?>