Operators
In PHP, operators are symbols that perform operations on one or more values (also known as operands) and return a result. There are several different types of operators in PHP, including:
- Arithmetic operators: perform basic arithmetic operations.
- Assignment operators: assign a value to a variable, such as the simple assignment operator.
- Comparison operators: compare two values and return a boolean result indicating whether the comparison is true or false.
- Logical operators: perform operations on boolean values and return a boolean result.
Operators are a fundamental building block of programming, and they are used to build expressions and control structures in PHP. Understanding how to use operators correctly is an essential skill for any PHP programmer.
What is an expression?
An expression is any piece of code that produces a value. It's like a small calculation or instruction that does something and gives you a result.
Let's go through some of these operators.
Arithmetic Operators
Arithmetic operators are symbols used to perform basic mathematical operations such as addition, subtraction, multiplication, division, modulo division, and exponentiation. The following are the most common arithmetic operators in PHP:
Addition
The addition operator (+
) adds two values together.
$a = 5;
$b = 2;
$c = $a + $b; // Result: 7
Subtraction
The subtraction operator (-
) subtracts one value from another.
$a = 5;
$b = 2;
$c = $a - $b; // Result: 3
Multiplication
The multiplication operator (*
) multiplies two values together.
$a = 5;
$b = 2;
$c = $a * $b; // Result: 10
Division
The division operator (/
) divides one value by another.
$a = 5;
$b = 2;
$c = $a / $b; // Result: 2.5
Modulo
Out of all the arithmetic operators, the modulo operator may feel like one of the strangest operators in PHP. The modulo division operator in PHP is represented by the percent symbol (%
). It performs modulo division, which returns the remainder of a division operation.
For example, if $a
is 5
and $b
is 2
, then $a % $b
would evaluate to 1
, because 5
divided by 2
is 2
with a remainder of 1
.
The modulo operator is useful in a variety of applications, such as testing for odd or even numbers, determining the last digit of a number, or finding the next multiple of a number. For instance, you can use the modulo operator to test if a number is odd or even by checking if its remainder is 0
or 1
when divided by 2
.
$a = 5;
$b = 2;
$c = $a % $b; // Result: 1
Exponentiation
The exponentiation operator in PHP is represented by two asterisks (**
). It calculates the power of a number, with the first operand being the base and the second operand being the exponent.
For example, if $base
is 2
and $exponent
is 8
, then $base ** $exponent
would evaluate to 256
, because 2
raised to the power of 8
is 256
.
The exponentiation operator was introduced in PHP 7.0, so it may not be available in older versions of PHP.
$base = 2;
$exponent = 8;
$result = $base ** $exponent; // Result: 256
Arithmetic operators are used in PHP to perform simple mathematical operations and are used frequently in many PHP programs. For example, you might use arithmetic operators to calculate the total cost of an order, to determine the average score on a test, or to perform any other type of calculation that involves basic arithmetic operations.
Assignment operators
Assignment operators in PHP are used to assign values to variables. The most commonly used assignment operator is the equal sign (=
), which assigns the value of the right operand to the left operand. For example:
$a = 5;
In this code, the value 5
is assigned to the variable $a
.
In addition to the basic assignment operator, there are several compound assignment operators in PHP that combine an operation with an assignment. These operators perform the operation on the values and then assign the result to the variable on the left side. Some of the most commonly used assignment operators in PHP include:
Addition assignment
The addition assignment (+=
) adds the value on the right side to the value of the variable on the left side and then assigns the result back to the left side.
In this example, $a += 5
is the equivalent of $a = $a + 5
.
$a = 5;
$a += 5; // Result: 10
Subtraction assignment
The subtraction assignment operator (-=
) subtracts the value on the right side from the value of the variable on the left side, and then assigns the result back to the left side.
In this example, $a -= 2
is the equivalent of $a = $a - 2
.
$a = 5;
$a -= 2; // Result: 3
Multiplication assignment
The multiplication assignment operator (*=
) multiplies the value of the variable on the left side by the value on the right side, and then assigns the result back to the left side.
In this example, $a *= 5
is the equivalent of $a = $a * 5
.
$a = 5;
$a *= 5; // Result: 25
Division assignment
The division assignment operator (/=
) divides the value of the variable on the left side by the value on the right side, and then assigns the result back to the left side.
In this example, $a /= 2
is the equivalent of $a = $a / 2
.
$a = 5;
$a /= 2; // Result: 2.5
Modulo assignment
The modulo assignment operator (%=
) divides the value of the variable on the left side by the value on the right side and then returns the remainder of the division operation.
In this example, $a %= 5
is the equivalent of $a = $a % 2
.
$a = 5;
$a %= 2; // Result: 1
Exponentiation assignment
The exponentiation assignment operator (**=
) performs exponentiation and assigns the result to the variable on the left side.
In this example, $a **= 5
is the equivalent of $a = $a ** 5
.
$a = 5;
$a **= 5; // Result: 25
Concatenation assignment
The concatenation assignment operator (.=
) performs concatenation and assigns the result to the variable on the left side.
In this example, $b .= " world
is the equivalent of $b = $a . " world"
.
$a = "Hello";
$b = $a . " world"; // Result: "Hello world"
Here's a summary of all the assignment operators.
Operator | Example | Equivalent | Operation |
---|---|---|---|
+= | $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 |
**= | $z **= $y | $x = $x ** $y | Exponentiation |
.= | $x .= $y | $x = $x . $y | Concatenation |
Comparison operators
Comparison operators in PHP are used to compare two values and determine whether a certain condition is true
or false
. The result of a comparison is a boolean value (true
or false
).
The following are the most common comparison operators in PHP:
Equal to
The equal to operator (==
) operator returns true
if the values are equal, and false
otherwise.
In this example, the $a
variable stores true
because 5
and 5
are equal to each other. The same isn't true for the $b
variable since 5
is not equal to 10
.
Lastly, the third example compares the integer 5
with a string "5"
. While they're completely different data types, PHP considers them to be equal. Behind the scenes, PHP changes the data types to be the same before comparing them.
$a = 5 == 5; // Result: true;
$b = 5 == 10; // Result: false;
$c = 5 == "5"; // Result: true;
Not equal to
The not equal to operator (!=
) returns true
if the values are not equal and false
otherwise.
Unlike before, the $a
variable will store false
even though the numbers are equal to each other. The numbers must not be the same value for a truthy value. On the other hand, the $b
variable will store true
since that's the case.
$a = 5 != 5; // Result: false;
$b = 5 != 10; // Result: true;
$c = 5 != "5"; // Result: false;
Identical to
The identical to operator (===
) returns true
if the values are equal and of the same type, and false
otherwise.
The examples are the same as the equal to operator, but there's one difference than before. The $c
variable will store false
even though the values match. Since their data types are different, PHP has determined that they don't match.
The ==
(equal to) operator and the ===
(identical) operator are used to compare values in PHP. The difference between the two is that the ==
operator performs a loose comparison, while the ===
operator performs a strict comparison.
You would want to use the ==
operator over the ===
operator when you need to compare values of different data types, and you are okay with the type conversion. On the other hand, you would want to use the ===
operator over the ==
operator when you need to perform a strict comparison and do not want type conversion.
In general, it's recommended to use the ===
operator over the ==
operator when performing comparisons in PHP, as it provides a more secure and accurate comparison.
$a = 5 === 5; // Result: true;
$b = 5 === 10; // Result: false;
$c = 5 === "5"; // Result: false;
Not identical to
The not identical to operator (!==
) returns true
if the values are not equal or not of the same type and false
otherwise.
$a = 5 !== 5; // Result: false;
$b = 5 !== 10; // Result: true;
$c = 5 !== "5"; // Result: true;
Greater than
The greater than operator (>
) returns true
if the left value is greater than the right value and false
otherwise.
$a = 10 > 5; // Result: true;
$b = 5 > 10; // Result: false;
Less than
The less than operator (<
) returns true
if the left value is less than the right value and false
otherwise.
$a = 5 < 10; // Result: true;
$b = 10 < 5; // Result: false;
Greater than or equal to
The greater than or equal to operator (>=
) returns true
if the left value is greater than or equal to the right value, and false
otherwise.
$a = 10 >= 5; // Result: true;
$b = 10 >= 10; // Result: true;
$c = 5 >= 10; // Result: false;
Less than or equal to
The less than or equal to operator (<=
) returns true
if the left value is less than or equal to the right value, and false
otherwise.
$a = 5 <= 10; // Result: true;
$b = 10 <= 10; // Result: true;
$c = 10 <= 5; // Result: false;
Here's a table with a summary of all the comparison operators.
Operator | Name | Description |
---|---|---|
== | Equal to | Return true if both operands are equal; otherwise, it returns false . |
!= | Not equal to | Return true if both operands are equal; otherwise, it returns false . |
=== | Identical to | Return true if both operands have the same data type and equal; otherwise, it returns false . |
!== | Not identical to | Return true if both operands are not equal or not have the same data type; otherwise, it returns false . |
> | Greater than | Return true if the operand on the left is greater than the operand on the right; otherwise, it returns false . |
>= | Greater than or equal to | Return true if the operand on the left is greater than or equal to the operand on the right; otherwise, it returns false . |
< | Less than | Return true if the operand on the left is less than the operand on the right; otherwise, it returns false . |
<= | Less than or equal to | Return true if the operand on the left is less than or equal to the operand on the right; otherwise, it returns false . |
Logical Operators
A logical operator in PHP is an operator that performs a logical operation on two or more values and returns a boolean value (true
or false
). The most common logical operators in PHP are &&
, ||
, and !
.
Logical operators are useful in PHP because they allow us to make decisions based on multiple conditions, which is an essential part of programming. They help us write more complex and powerful code by allowing us to control the flow of execution based on different conditions.
Let's look at these operators.
The and operator
The and operator (&&
) in PHP is a logical operator that is used to check if two conditions are both true
. If both conditions are true
, the operator returns true
, and if either one or both of the conditions are false, it returns false
.
What is a condition?
A condition in PHP is a statement that evaluates to either true
or false
. Conditions can be created using comparison operators such as ==
(equal to), !=
(not equal to), >
(greater than), <
(less than), >=
(greater than or equal to), and <=
(less than or equal to). Logical operators can be used to combine multiple conditions and make more complex decisions.
In this example, the &&
operator checks if $age >= 18
and $age <= 65
are both true
. If both conditions are true
, the $canWork
variable will store true
.
The &&
operator is useful because it allows us to write code that makes decisions based on multiple conditions. For example, we could use it to check if someone is eligible for a job based on their age, education, and work experience. By combining multiple conditions with the &&
operator, we can write more sophisticated and powerful code.
$age = 20;
// Result: true;
$canWork = $age >= 18 && $age <= 65;
The or operator
The or operator (||
) in PHP is the logical "or" operator. It is used to combine two conditions and returns true
if at least one of the conditions is true
.
In this code, the condition $isRaining || $isSnowing
is checking if either $isRaining
or $isSnowing
is true
. If either of them is true
, the $isWeatherBad
variable gets set to true
.
The ||
operator is useful in situations where multiple conditions need to be checked and the program should take action if any of them is true
. It allows you to write concise and readable code, as you can check multiple conditions with a single line of code.
$isRaining = true;
$isSnowing = false;
// Result: true
$isWeatherBad = $isRaining || $isSnowing;
The not operator
The !
operator in PHP is the logical "not" operator. It is used to negate or reverse the value of a boolean expression. It returns true
if the expression is false
, and false
if the expression is true
.
In this code, the condition !$isRaining
is checking if $isRaining
is false
. If it is false, the $isWeatherGood
variable will be set to true
. The !
operator is useful in situations where you want to check if a condition is false
, or you want to negate the value of a boolean expression.
$isRaining = false;
$isWeatherGood = !$isRaining; // Result: true
$isSnowing = true;
$isWeatherGood = !$isSnowing; // Result: false
Short-circuiting
Short-circuiting in PHP refers to a feature of the &&
operator that stops evaluating its expressions as soon as it can determine the overall result of the operation. For example, consider the following code:
$debugMode = false;
$debugMode && print("Debugging Code");
In this code, the condition $debugMode && print("Debugging Code");
checks if the $debugMode
variable is true
. However, since this variable is false
, the second condition is never evaluated. Because we already know the overall result will be false
. The PHP interpreter takes advantage of this fact and stops evaluating $b as soon as it knows the result.
What is the print function?
The print
function is an alternative solution to the echo
keyword. It'll output content onto the page similar to the echo
keyword.
If we were to set the $debugMode
variable to true
, the reverse would occur. Since it's true
, the print
function gets executed and the message appears on the screen.
$debugMode = true;
$debugMode && print("Debugging mode turned on");
Short-circuiting helps to improve the performance of PHP code by avoiding unnecessary calculations and evaluations. In some cases, it can also help to prevent errors or unexpected results by avoiding the evaluation of expressions that would cause errors or have side effects.
Key takeaways
- Arithmetic operators perform basic arithmetic operations.
- Assignment operators assign a value to a variable, such as the simple assignment operator.
- Comparison operators compare two values and return a boolean result indicating whether the comparison is true or false.
- Logical operators perform operations on boolean values and return a boolean result.