Contents

PHP Operators

PHP Operators

Operators are fundamental tools in any programming language, and PHP is no exception. They allow us to perform various operations on values or variables. To put it simply, operators take values (or operands), apply a specified operation, and return a result. For instance, in the expression “5 + 3 = 8,” the + symbol is an operator. It takes the values 5 and 3, adds them, and produces 8.

PHP provides several types of operators to handle different operations, such as arithmetic operations (e.g., addition, subtraction), logical operations (e.g., AND, OR), increment/decrement operations, and more. These operators are represented by symbols, and they help in manipulating variables or values efficiently. Below is a breakdown of the different groups of operators available in PHP:

  • Arithmetic Operators
  • Logical or Relational Operators
  • Comparison Operators
  • Conditional or Ternary Operators
  • Assignment Operators
  • Spaceship Operators (Introduced in PHP 7)
  • Array Operators
  • Increment/Decrement Operators
  • String Operators

1. Arithmetic Operators: Arithmetic operators are used to perform basic mathematical calculations, such as addition, subtraction, multiplication, and so on. The table below lists the common arithmetic operators in PHP, along with their syntax and operations.

OperatorNameSyntaxOperation
+Addition$a + $bAdds two operands
-Subtraction$a - $bSubtracts second operand from first
*Multiplication$a * $bMultiplies two operands
/Division$a / $bDivides first operand by second
**Exponentiation$a ** $bRaises $a to the power of $b
%Modulus$a % $bReturns the remainder of division

Example:

				
					<?php
$a = 15;
$b = 4;

echo "Addition: " . ($a + $b) . "\n";
echo "Subtraction: " . ($a - $b) . "\n";
echo "Multiplication: " . ($a * $b) . "\n";
echo "Division: " . ($a / $b) . "\n";
echo "Exponentiation: " . ($a ** $b) . "\n";
echo "Modulus: " . ($a % $b) . "\n";
?>

				
			

Output:

				
					Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Exponentiation: 50625
Modulus: 3

				
			

2. Logical or Relational Operators: These operators are primarily used with conditional expressions to check whether certain conditions are met (i.e., whether they are true or false). Logical operators are key in making decisions within the code.

OperatorNameSyntaxOperation
andLogical AND$a and $bTrue if both $a and $b are true
orLogical OR$a or $bTrue if either $a or $b is true
xorLogical XOR$a xor $bTrue if only one operand is true, but not both
&&Logical AND$a && $bTrue if both $a and $b are true (same as and)
` `Logical OR
!Logical NOT!$aTrue if $a is false

Example:

				
					<?php
$a = 40;
$b = 25;

if ($a == 40 and $b == 25)
    echo "and Success\n";

if ($a == 40 or $b == 20)
    echo "or Success\n";

if ($a == 40 xor $b == 30)
    echo "xor Success\n";

if ($a == 40 && $b == 25)
    echo "&& Success\n";

if ($a == 40 || $b == 20)
    echo "|| Success\n";

if (!$b)
    echo "! Success\n";
?>

				
			

Output:

				
					and Success
or Success
xor Success
&& Success
|| Success

				
			

3. Comparison Operators: Comparison operators compare two values and return a boolean (true or false) based on whether the condition is satisfied.

OperatorNameSyntaxOperation
==Equal$a == $bReturns true if $a equals $b
!=Not equal$a != $bReturns true if $a does not equal $b
<Less than$a < $bReturns true if $a is less than $b
>Greater than$a > $bReturns true if $a is greater than $b
<=Less or equal$a <= $bReturns true if $a is less than or equal to $b
>=Greater or equal$a >= $bReturns true if $a is greater than or equal to $b

Example:

				
					<?php
$x = 70;
$y = 30;

var_dump($x == $y);
var_dump($x != $y);
var_dump($x < $y);
var_dump($x > $y);
?>

				
			

Output:

				
					bool(false)
bool(true)
bool(false)
bool(true)

				
			

PHP Bitwise Operators

Bitwise Operators are used to perform bit-level operations on the operands. The operands are first converted to binary, and then bit-level calculations are performed. Operations like addition, subtraction, and multiplication can be performed at the bit level for faster processing. In PHP, the bitwise operators include:

& (Bitwise AND)

This is a binary operator, meaning it works on two operands. The Bitwise AND operator in PHP takes two numbers as operands and performs an AND operation on each bit. The result is 1 only if both bits are 1.

Syntax:

				
					$First & $Second

				
			

Example:

				
					Input: $First = 6, $Second = 4
				
			

Output:

				
					The bitwise & of these values will be 4.
				
			

Explanation: Binary representation of 6 is 0110, and 4 is 0100. Therefore, their bitwise & will be 0100, which is 4.

| (Bitwise OR)

This binary operator performs an OR operation on each bit of the operands. The result is 1 if any of the two bits are 1.

Syntax:

				
					$First | $Second

				
			

Example:

				
					Input: $First = 6, $Second = 4
				
			

Output:

				
					The bitwise | of these values will be 6.
				
			

Explanation: Binary representation of 6 is 0110, and 4 is 0100. Therefore, their bitwise | will be 0110, which is 6.

^ (Bitwise XOR)

This binary operator is also known as the Exclusive OR operator. It returns 1 if the two bits are different.

Syntax:

				
					$First ^ $Second

				
			

Example:

				
					Input: $First = 6, $Second = 4
				
			

Output:

				
					The bitwise ^ of these values will be 2.
				
			

Explanation: Binary representation of 6 is 0110, and 4 is 0100. Therefore, their bitwise ^ will be 0010, which is 2.

~ (Bitwise NOT)

This is a unary operator, meaning it works on only one operand. It inverts all the bits of the operand.

Syntax:

				
					~$number

				
			

Example:

				
					Input: $number = 6
				
			

Output:

				
					The bitwise ~ of this number will be -7.
				
			

Explanation: Binary representation of 6 is 0110. Therefore, its bitwise ~ will be 1001 (inverted), which corresponds to -7 in two’s complement representation.

<< (Bitwise Left Shift)

This binary operator shifts the bits of the first operand to the left. The second operand determines the number of positions to shift.

Syntax:

				
					$First << $Second

				
			

Example:

				
					Input: $First = 6, $Second = 2
				
			

Output:

				
					The bitwise << of these values will be 24.
				
			

Explanation: Binary representation of 6 is 0110. Left-shifting it by 2 positions gives 11000, which is 24.

>> (Bitwise Right Shift)

This binary operator shifts the bits of the first operand to the right. The second operand determines the number of positions to shift.

Syntax:

				
					$First >> $Second

				
			

Example:

				
					Input: $First = 6, $Second = 2
				
			

Output:

				
					The bitwise >> of these values will be 1.
				
			

Explanation: Binary representation of 6 is 0110. Right-shifting it by 2 positions gives 0001, which is 1.

Example:

				
					<?php 
    // PHP code to demonstrate Bitwise Operators 
    
    // Bitwise AND 
    $First = 6; 
    $second = 4; 
    $answer = $First & $second; 
    print_r("Bitwise & of 6 and 4 is $answer"); 
    print_r("\n"); 
    
    // Bitwise OR 
    $answer = $First | $second; 
    print_r("Bitwise | of 6 and 4 is $answer"); 
    print_r("\n"); 
    
    // Bitwise XOR 
    $answer = $First ^ $second; 
    print_r("Bitwise ^ of 6 and 4 is $answer"); 
    print_r("\n"); 
    
    // Bitwise NOT 
    $answer = ~$First; 
    print_r("Bitwise ~ of 6 is $answer"); 
    print_r("\n"); 
    
    // Bitwise Left Shift 
    $second = 2; 
    $answer = $First << $second; 
    print_r("6 << 2 will be $answer"); 
    print_r("\n"); 
    
    // Bitwise Right Shift 
    $answer = $First >> $second; 
    print_r("6 >> 2 will be $answer"); 
    print_r("\n"); 
?>

				
			

Output:

				
					Bitwise & of 6 and 4 is 4
Bitwise | of 6 and 4 is 6
Bitwise ^ of 6 and 4 is 2
Bitwise ~ of 6 is -7
6 << 2 will be 24
6 >> 2 will be 1

				
			

PHP Ternary Operator

The if-else and switch statements are commonly used for condition evaluation and determining the flow of a program. Another option for simpler conditional statements is the ternary operator, which offers a more concise way to handle basic conditions.

Ternary Operator:

The ternary operator (?:) is a compact conditional operator that allows you to quickly check a condition and return one of two values based on the result. It works from left to right and is called “ternary” because it takes three operands: a condition, a value for true, and a value for false.

Syntax:

				
					(Condition) ? (TrueStatement) : (FalseStatement);

				
			
  • Condition: The expression to evaluate, which returns a boolean value.
  • TrueStatement: The statement executed if the condition evaluates to true.
  • FalseStatement: The statement executed if the condition evaluates to false.

Syntax:

				
					$variable = (Condition) ? (TrueStatement) : (FalseStatement);

				
			

Example:

				
					<?php
  $score = 80;
  print ($score >= 75) ? "Pass" : "Fail";
?>

				
			

Output:

				
					Pass

				
			
Advantages of the Ternary Operator:

1. It makes code shorter compared to traditional if-else statements.
2. It reduces the overall length of conditional logic.
3. It improves code readability by condensing conditional statements.
4. The code becomes simpler and easier to follow.

Example:

In this example, if the value of $num is greater than 10, 50 will be returned and assigned to $result. Otherwise, 15 will be returned and assigned to $result.

				
					<?php
  $num = 8;
  $result = $num > 10 ? 50 : 15;
  echo "Value of result is " . $result;
?>

				
			

Output:

				
					Value of result is 15

				
			

Example 2:

In this example, if the value of $temperature is 30 or higher, “Hot” will be displayed. Otherwise, “Cold” will be displayed.

				
					<?php
  $temperature = 28;
  echo ($temperature >= 30) ? "Hot" : "Cold";
?>

				
			

Output:

				
					Cold

				
			
When to Use the Ternary Operator:

The ternary operator is best used when you want to simplify an if-else block that simply assigns values to variables based on a condition. Its primary benefit is that it condenses a lengthy if-else block into a single line, which enhances both readability and simplicity. It is especially useful for assigning variables after form submissions or handling small conditional checks.

Example:

Original Code:

				
					<?php
if (isset($_POST['City'])) {
    $city = $_POST['City'];
} else {
    $city = null;
}

if (isset($_POST['Country'])) {
    $country = $_POST['Country'];
} else {
    $country = null;
}
?>

				
			

This can be reduced to the following, using the ternary operator:

				
					<?php
$city = isset($_POST['City']) ? $_POST['City'] : null;
$country = isset($_POST['Country']) ? $_POST['Country'] : null;
?>

				
			

Example:

				
					<?php
  // Example 1: Simple ternary operation
  $num = 8;
  $result = $num > 10 ? 50 : 15;
  echo "Value of result is " . $result;
  echo "\n";

  // Example 2: Conditional display
  $temperature = 28;
  echo ($temperature >= 30) ? "Hot" : "Cold";
  echo "\n";
?>

				
			

Output:

				
					Value of result is 15
Cold