PHP Assignment Operators: Efficient Variable Assignments

Rumman Ansari   Software Engineer   2024-07-09 10:08:34   5415  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

The PHP assignment operators are used with numeric values to write a value to a variable.

The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right.

Assignment Same as... Description
x = y x = y The left operand gets set to the value of the expression on the right
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus

Example: The left operand gets set to the value of the expression on the right

Code:



<!DOCTYPE html>
<html>
<body>

<?php
$x = 10;  
echo $x;
?>  

</body>
</html>



Output:

This will produce the following result



10


Example: Addition

Code:



<!DOCTYPE html>
<html>
<body>

<?php
$x = 20;  
$x += 100;

echo $x;
?>  

</body>
</html>



Output:

This will produce the following result



120


Example: Subtraction

Code:



<!DOCTYPE html>
<html>
<body>

<?php
$x = 50;
$x -= 30;

echo $x;
?>  

</body>
</html>



Output:

This will produce the following result



20


Example: Multiplication

Code:



<!DOCTYPE html>
<html>
<body>

<?php
$x = 10;  
$y = 6;

echo $x * $y;
?>  

</body>
</html>



Output:

This will produce the following result



60


Example: Division

Code:



<!DOCTYPE html>
<html>
<body>

<?php
$x = 10;
$x /= 5;

echo $x;
?>  

</body>
</html>



Output:

This will produce the following result



2


Example: Modulus

Code:



<!DOCTYPE html>
<html>
<body>

<?php
$x = 15;
$x %= 4;

echo $x;
?>  

</body>
</html>


Output:

This will produce the following result



3


MCQ Available

There are 1 MCQs available for this topic.

1 MCQ