What Are Operators in PHP?

What Are Operators in PHP?

👋 Hey there, PHP developer! Whether you’re just starting out with PHP or brushing up your skills, operators in PHP are something you can’t avoid — and honestly, you shouldn’t! Think of them as the tools that let you do things with your data — add, compare, assign, and so much more. 🧰

In this post, we’ll break down PHP operators into bite-sized pieces with real examples, so you can master them quickly and confidently.

🔍 What Are Operators in PHP?

Operators in PHP are symbols that perform operations on variables and values. They’re used to:

  • Do math
  • Compare values
  • Assign values
  • Combine conditions
  • Work with bits (for the techy crowd)

➕ 1. Arithmetic Operators

Arithmetic operators in PHP are used to perform basic mathematical operations such as addition, subtraction, multiplication, division, and more.

OperatorNameExampleDescription
+Addition$a + $bAdds $a and $b
-Subtraction$a - $bSubtracts $b from $a
*Multiplication$a * $bMultiplies $a by $b
/Division$a / $bDivides $a by $b
%Modulus (Remainder)$a % $bReturns the remainder of $a divided by $b

💡 Example:

PHP
<?php
$a = 10;
$b = 3;

echo $a + $b;   // 13
echo $a - $b;   // 7
echo $a * $b;   // 30
echo $a / $b;   // 3.333...
echo $a % $b;   // 1
?>

🔁 2. Assignment Operators

Assignment operators in PHP are used to assign values to variables. The most basic is the = operator, but there are many shorthand operators that combine assignment with arithmetic operations.

OperatorNameExampleSame AsDescription
=Simple assignment$a = 5Assigns value 5 to variable $a
+=Add and assign$a += 3$a = $a + 3Adds and assigns the result to $a
-=Subtract and assign$a -= 2$a = $a - 2Subtracts and assigns the result to $a
*=Multiply and assign$a *= 4$a = $a * 4Multiplies and assigns the result to $a
/=Divide and assign$a /= 2$a = $a / 2Divides and assigns the result to $a
%=Modulus and assign$a %= 3$a = $a % 3Assigns the remainder of $a ÷ 3 to $a

💡 Example:

PHP
<?php
$a = 5;
$a += 3; // $a is now 8
$a -= 1; // $a is now 7
$a *= 2; // $a is now 14
$a /= 7; // $a is now 2
echo $a;
?>

🔍 3. Comparison Operators

Comparison operators in PHP are used to compare two values. They return a Boolean result: true or false. These operators are commonly used in conditional statements like if, while, and loops.

OperatorNameExampleDescription
==Equal$a == $bReturns true if $a is equal to $b (type is ignored).
===Identical$a === $bReturns true if $a is equal to $b and of the same type.
!=Not equal$a != $bReturns true if $a is not equal to $b.
<>Not equal$a <> $bSame as !=.
!==Not identical$a !== $bReturns true if $a is not equal or not of same type as $b.
<Less than$a < $bReturns true if $a is less than $b.
>Greater than$a > $bReturns true if $a is greater than $b.
<=Less than 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
$a = 5;
$b = "5";

var_dump($a == $b);   // true  (values are equal, type ignored)
var_dump($a === $b);  // false (different types: int vs string)

var_dump($a != $b);   // false
var_dump($a !== $b);  // true

var_dump($a < 10);    // true
var_dump($a >= 5);    // true

⚙️ 4. Logical Operators

Logical operators in PHP are used to combine multiple conditions or perform logical operations. They return true or false based on the truth values of the expressions.

OperatorNameExampleDescription
andLogical AND$a and $bReturns true if both $a and $b are true
&&Logical AND$a && $bSame as and but higher precedence
orLogical OR$a or $bReturns true if either $a or $b is true
``Logical OR
!Logical NOT!$aReturns true if $a is not true
xorLogical XOR$a xor $bReturns true if only one of $a or $b is true, but not both

⚠️ and vs && (and or vs ||)

  • && and || have higher precedence than and and or.
  • This affects how expressions are evaluated when combined with = and other operators.

💡 Example:

PHP
$a = false;
$b = true;

var_dump($a && $b);   // false
var_dump($a || $b);   // true
var_dump(!$a);        // false
var_dump($a xor $b);  // true (only one is true)

$result1 = $a && $b; // evaluates as expected: false
$result2 = $a and $b; // assigns $a first, then evaluates: ($result2 = $a), then `and $b`

// Better practice:
$age = 25;
$hasID = true;

if ($age >= 18 && $hasID) {
    echo "Access granted.";
} else {
    echo "Access denied.";
}

🧮 5. Increment/Decrement Operators

Increment and decrement operators in PHP are used to increase or decrease a variable’s value by 1. These are commonly used in loops and counters.

OperatorNameExampleDescription
++$aPre-increment$a = 5; ++$a;Increments $a by 1 before returning its value
$a++Post-increment$a = 5; $a++;Returns $a, then increments by 1
--$aPre-decrement$a = 5; --$a;Decrements $a by 1 before returning its value
$a--Post-decrement$a = 5; $a--;Returns $a, then decrements by 1

💡 Example:

PHP
$a = 5;

// Pre-increment
echo ++$a;  // Outputs 6 (increments, then returns)
echo $a;    // Still 6

// Post-increment
$a = 5;
echo $a++;  // Outputs 5 (returns, then increments)
echo $a;    // Now 6

// Pre-decrement
$b = 5;
echo --$b;  // Outputs 4

// Post-decrement
$b = 5;
echo $b--;  // Outputs 5
echo $b;    // Now 4
⚠️ Note:
  • Use pre-increment (++$a) when you want to increment before the value is used.
  • Use post-increment ($a++) when you want to use the value first, then increment.

🧩 6. String Operators

String operators in PHP are used to manipulate and combine strings. PHP provides a small but powerful set of string operators.

OperatorNameExampleDescription
.Concatenation Operator$a . $bJoins two strings together
.=Concatenation Assignment$a .= $bAppends the right string to the left variable

💡 Example:

PHP
// Concatenation
$firstName = "John";
$lastName = "Doe";

$fullName = $firstName . " " . $lastName;
echo $fullName; // Output: John Doe

// Concatenation Assignment
$greeting = "Hello";
$greeting .= " World!";
echo $greeting; // Output: Hello World!

⚡ 7. Bitwise Operators

Here’s a complete explanation of the Bitwise, Array, Null Coalescing, and Ternary operators in PHP, with examples:

OperatorNameExampleDescription
&AND$a & $bBits that are set in both $a and $b
``OR`$a
^XOR$a ^ $bBits set in one but not both
~NOT~$aInverts the bits
<<Left Shift$a << 1Shifts bits to the left (multiplies by 2)
>>Right Shift$a >> 1Shifts bits to the right (divides by 2)

💡 Example:

PHP
$a = 5;    // 0101 in binary
$b = 3;    // 0011 in binary

echo $a & $b; // 1 (0001)
echo $a | $b; // 7 (0111)
echo $a ^ $b; // 6 (0110)
echo ~$a;     // -6 (inverts bits of 5)
echo $a << 1; // 10 (shift left: 1010)
echo $a >> 1; // 2 (shift right: 0010)

📚 7. Array Operators

Used to compare or combine arrays.

OperatorNameExampleDescription
+Union$a + $bCombines arrays (preserves keys from the left)
==Equality$a == $btrue if arrays have the same key/value pairs
===Identity$a === $btrue if arrays are equal and have same order/types
!= / <>Inequality$a != $btrue if arrays are not equal
!==Non-identity$a !== $btrue if arrays are not identical

💡 Example:

PHP
$a = ["a" => 1, "b" => 2];
$b = ["b" => 2, "a" => 1];

var_dump($a == $b);   // true
var_dump($a === $b);  // false (order different)
var_dump($a + $b);    // ['a' => 1, 'b' => 2]

❔ 8. Null Coalescing Operator (??)

Returns the first operand if it’s set and not null, otherwise the second.

OperatorExampleDescription
??$a = $_GET['id'] ?? 0;If $_GET['id'] is set, use it; otherwise use 0

💡 Example:

PHP
$username = $_POST['username'] ?? 'Guest';
echo $username;

This avoids warnings like undefined index and provides a default.

❓ 9. Ternary Operator (?:)

A short form of if...else. Often used to assign values based on a condition.

SyntaxDescription
condition ? true_result : false_resultIf condition is true, returns true_result, otherwise false_result

💡 Example:

PHP
$age = 20;
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status;  // Output: Adult

## Shorthand version (PHP 5.3+):
$user = $_GET['user'] ?: 'Guest';  // If `$_GET['user']` is falsy, use 'Guest'

Final Thoughts

Operators are the muscles of PHP — they do the heavy lifting when it comes to logic, math, decisions, and data manipulation. Whether you’re calculating prices, checking login details, or building dynamic content, you’ll be using operators a lot.

So keep this guide handy and practice each one! 💪

Got a favorite or tricky operator that always confuses you? Drop it in the comments and let’s untangle it together! 👇


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *