Operators in PHP
Operators in PHP are symbols or keywords that perform operations on variables and values. They are essential in building logical expressions, performing arithmetic, and managing data.
What is operator precedence in PHP with example?
Operator Precedence in PHP refers to the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated before operators with lower precedence. This is important to understand to ensure expressions return the expected results.
Operator Precedence Example:
Consider the following example:
$a = 5;
$b = 10;
$c = 3;
$result = $a + $b * $c;
echo $result;
Explanation:
- The
*(multiplication) operator has higher precedence than the+(addition) operator. - Therefore,
$b * $cis evaluated first, which results in10 * 3 = 30. - After that,
$a + 30is evaluated, resulting in5 + 30 = 35.
Operator Precedence Order in PHP:
- Parentheses
()have the highest precedence. - Arithmetic operators like
*,/,%have higher precedence than+,-. - Comparison operators like
==,!=,<,>have lower precedence. - Logical operators like
&&,||,!have lower precedence than comparison operators.
Types of Operators in PHP
Here are the various operators in PHP:
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Increment/Decrement Operators
- Logical Operators
- String Operators
- Array Operators
- Conditional (Ternary) Operator
- Execution Operator
- Error Control Operator
- Type Operators
- Null Coalescing Operator
- Spaceship Operator
- Bitwise Operators
1. Arithmetic Operators
Arithmetic operators in PHP are used to perform mathematical operations like addition, subtraction, multiplication, division, and modulus. They include +, -, *, /, and % for basic calculations.
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | $x + $y |
Sum of $x and $y |
- |
Subtraction | $x - $y |
Difference of $x and $y |
* |
Multiplication | $x * $y |
Product of $x and $y |
/ |
Division | $x / $y |
Quotient of $x and $y |
% |
Modulus | $x % $y |
Remainder of $x / $y |
** |
Exponentiation | $x ** $y |
$x raised to the power of $y |
Example:
<?php
$x = 10;
$y = 3;
echo $x + $y; // Output: 13
echo $x % $y; // Output: 1
?>
2. Assignment Operators
Assignment operators in PHP are used to assign values to variables. The most common assignment operator is =, but there are compound operators like +=, -=, *=, /=, etc., for shorthand operations.
| Operator | Example | Same As |
= |
$x = 5 |
Assigns 5 to $x |
+= |
$x += 3 |
$x = $x + 3 |
-= |
$x -= 2 |
$x = $x - 2 |
*= |
$x *= 4 |
$x = $x * 4 |
/= |
$x /= 2 |
$x = $x / 2 |
%= |
$x %= 3 |
$x = $x % 3 |
3. Comparison Operators
Comparison operators in PHP are used to compare two values and return a boolean result (true or false). They include == (equal), != (not equal), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to).
| Operator | Name | Example | Result |
== |
Equal | $x == $y |
TRUE if $x equals $y |
=== |
Identical | $x === $y |
TRUE if $x equals $y and same type |
!= |
Not Equal | $x != $y |
TRUE if $x is not equal to $y |
<> |
Not Equal | $x <> $y |
TRUE if $x is not equal to $y |
!== |
Not Identical | $x !== $y |
TRUE if $x is not identical to $y |
> |
Greater Than | $x > $y |
TRUE if $x is greater than $y |
< |
Less Than | $x < $y |
TRUE if $x is less than $y |
>= |
Greater or Equal | $x >= $y |
TRUE if $x is greater or equal to $y |
<= |
Less or Equal | $x <= $y |
TRUE if $x is less or equal to $y |
4. Increment/Decrement Operators
Increment (++) and decrement (--) operators in PHP are used to increase or decrease a variable's value by 1, respectively. They can be used in both prefix (++$a) and postfix ($a++) forms, affecting the operation order.
| Operator | Name | Description |
++$x |
Pre-increment | Increments $x, then returns $x |
$x++ |
Post-increment | Returns $x, then increments $x |
--$x |
Pre-decrement | Decrements $x, then returns $x |
$x-- |
Post-decrement | Returns $x, then decrements $x |
5. Logical Operators
Logical operators in PHP are used to combine conditional statements and control the flow of the program based on multiple conditions.
Here's a table summarizing logical operators in PHP with definitions and examples:
| Operator | Name | Description | Result |
|---|---|---|---|
and |
Logical AND | Returns true if both conditions are true. |
False |
&& |
Logical AND (High precedence) | Same as and but with higher precedence. |
True |
or |
Logical OR | Returns true if at least one condition is true. |
True |
! |
Logical NOT | Reverses the result of the condition. | False |
xor |
Logical XOR | Returns true if only one condition is true, but not both. |
True |
6. String Operators
String operators in PHP are used to concatenate or combine strings. The . (dot) operator is used for concatenation, while the .= operator appends a string to an existing variable.
| Operator | Name | Example | Result |
. |
Concatenation | $txt1 . $txt2 |
Combines $txt1 and $txt2 |
.= |
Concatenation Assignment | $txt1 .= $txt2 |
Appends $txt2 to $txt1 |
7. Conditional (Ternary) Operator
The conditional (ternary) operator in PHP is a shorthand for if-else statements. It has the form condition ? value_if_true : value_if_false, evaluating the condition and returning the corresponding value based on the result.
| Operator | Example | Result |
? : |
$x = ($a > $b) ? $a : $b; |
Returns $a if $a > $b, else $b |
8. Array Operators
Used to compare and combine arrays.
| Operator | Name | Example | Result |
+ |
Union | $x + $y |
Union of $x and $y |
== |
Equality | $x == $y |
TRUE if $x and $y have the same key/value pairs |
=== |
Identity | $x === $y |
TRUE if $x and $y have same key/value pairs in same order and type |
!= |
Inequality | $x != $y |
TRUE if $x is not equal to $y |
<> |
Inequality | $x <> $y |
TRUE if $x is not equal to $y |
!== |
Non-identity | $x !== $y |
TRUE if $x is not identical to $y |
9. Execution Operator in PHP
- The Execution Operator in PHP is represented by backticks ( ` ` ).
- It is used to execute shell commands directly from a PHP script.
- The result of the command is returned as a string.
Example in Tabular Form:
| Code | Description | Output |
|---|---|---|
php $output = `ls`; echo $output; |
Lists files in the current directory | List of directory files |
php $date = `date`; echo $date; |
Displays the current date and time | Current date and time |
php $whoami = `whoami`; echo $whoami; |
Shows the current user running the script | Username |
php $uptime = `uptime`; echo $uptime; |
Displays system uptime information | System uptime info |
php $ping = `ping -c 1 google.com`; echo $ping; |
Pings Google once and displays the result | Ping response details |
<?php
// Example 1: List files in the current directory
$files = `ls`;
echo "Files in the current directory:";
echo $files;
// Example 2: Display current date and time
$currentDate = `date`;
echo "Current Date and Time:";
echo $currentDate;
// Example 3: Show the current user running the script
$user = `whoami`;
echo "Current User:";
echo $user;
// Example 4: Display system uptime information
$uptime = `uptime`;
echo "System Uptime:";
echo $uptime;
// Example 5: Ping google.com once and display the result
$pingResult = `ping -c 1 google.com`;
echo "Ping Result:";
echo $pingResult;
?>
10. Error Control Operator in PHP
- The Error Control Operator in PHP is represented by the at symbol ( @ ).
- It is used to suppress error messages that would normally be displayed when a certain expression fails.
- When prepended to an expression, any runtime errors generated by that expression are ignored.
How It Works:
- Without
@, PHP will display any errors or warnings for problematic code. - With
@, PHP will suppress those errors, and the script will continue running without displaying the error message.
<?php
// Example 1: Without Error Control Operator
$file = fopen("non_existing_file.txt", "r");
// Example 2: With Error Control Operator
$file = @fopen("non_existing_file.txt", "r");
if (!$file)
{
echo "File could not be opened.";
}
?>
11. Type Operators in PHP
Type Operators in PHP are used to determine or modify the data type of variables. They help in checking, converting, and handling different data types during the execution of a script.
Types of Type Operators:
instanceofOperator- Type Casting Operators
1. instanceof Operator
- The
instanceofoperator is used to check if an object is an instance of a specific class or a subclass. - It returns
trueif the object belongs to the class, otherwisefalse.
Syntax: $object instanceof ClassName;
<?php
class Car {}
$myCar = new Car();
if ($myCar instanceof Car)
{
echo "myCar is an instance of the Car class.";
}
else
{
echo "myCar is NOT an instance of the Car class.";
}
?>
2. Type Casting Operators
- Type Casting is used to convert a variable from one data type to another explicitly.
- PHP supports several type casting operators to convert variables into specific data types.
Common Type Casting Operators:
| Operator | Description |
|---|---|
(int) or (integer) |
Converts to integer |
(bool) or (boolean) |
Converts to boolean |
(float) or (double) or (real) |
Converts to float |
(string) |
Converts to string |
(array) |
Converts to array |
(object) |
Converts to object |
(unset) |
Converts to NULL |
12. Null Coalescing Operator in PHP
The Null Coalescing Operator in PHP is represented by ??. It is used to check if a variable is set and not null. If the variable exists and is not null, its value is returned; otherwise, a default value is returned.
Syntax:
$result = $variable ?? $default_value;
- If
$variableis set and not null →$result = $variable - If
$variableis not set or is null →$result = $default_value
<?php
$username = $_GET['user'] ?? 'Guest';
echo "Hello, " . $username;
?>
Explanation:
If the URL has a user parameter (like ?user=John), it will display "Hello, John".
If the user parameter is missing, it will display "Hello, Guest".
13. Spaceship Operator in PHP
The Spaceship Operator in PHP is represented by <=>. It is used for combined comparison of two expressions. It returns:
-1if the left-hand side is less than the right-hand side.0if both sides are equal.1if the left-hand side is greater than the right-hand side.
Syntax:
$result = $a <=> $b;
Return Values:
| Condition | Return Value |
|---|---|
$a < $b |
-1 |
$a == $b |
0 |
$a > $b |
1 |
14. Bitwise Operators in PHP
Bitwise Operators in PHP operate on variables at the binary level. They perform operations on the individual bits of integer values. These operators are commonly used in tasks like low-level programming, bitmasking, and performance optimization.
List of Bitwise Operators in PHP:
| Operator | Name | Description |
|---|---|---|
& |
AND | Sets each bit to 1 if both corresponding bits are 1. |
| ` | ` | OR |
^ |
XOR (Exclusive OR) | Sets each bit to 1 if only one of the corresponding bits is 1. |
~ |
NOT | Inverts all bits (1 becomes 0, and 0 becomes 1). |
<< |
Left Shift | Shifts bits to the left, adding zeros on the right. |
>> |
Right Shift | Shifts bits to the right, discarding bits on the right. |
Example of Bitwise Operations:
Let's consider two integers:
- A = 5 (in binary:
0101) - B = 3 (in binary:
0011)
| Operation | Code | Binary Result | Decimal Result |
|---|---|---|---|
| AND | $result = 5 & 3; |
0001 |
1 |
| OR | `$result = 5 | 3;` | 0111 |
| XOR | $result = 5 ^ 3; |
0110 |
6 |
| NOT | $result = ~5; |
...11111010 |
-6 (Two's complement) |
| Left Shift | $result = 5 << 1; |
1010 |
10 |
| Right Shift | $result = 5 >> 1; |
0010 |
2 |