Operators in PHP

Alright, now that you’ve mastered variables and data types, let’s talk about operators—the little symbols that make your code do some actual work! Whether it’s math, comparisons, or logic, PHP operators have got you covered. Buckle up, because things are about to get interesting!

What is an Operator?

An operator is a special symbol that performs operations on values and variables. Think of them as PHP’s action heroes—always ready to calculate, compare, and make logical decisions!

$a = 10;
$b = 5;
$sum = $a + $b; // Using the + operator
echo $sum; // Output: 15

Types of Operators in PHP

PHP has several types of operators, and we’ll break them down one by one.

Arithmetic Operators

These operators perform basic math operations.

$a = 10;
$b = 3;

echo $a + $b; // Addition (Output: 13)
echo $a - $b; // Subtraction (Output: 7)
echo $a * $b; // Multiplication (Output: 30)
echo $a / $b; // Division (Output: 3.33)
echo $a % $b; // Modulus (Output: 1, remainder of 10/3)

Assignment Operators

Used to assign values to variables.

$x = 5; // Assigning 5 to $x
$x += 2; // Equivalent to $x = $x + 2 (Now $x is 7)
$x -= 3; // Equivalent to $x = $x - 3 (Now $x is 4)

Comparison Operators

Used to compare values.

$a = 10;
$b = "10";

var_dump($a == $b); // true (values are equal, ignoring type)
var_dump($a === $b); // false (strict comparison, types are different)
var_dump($a != $b); // false (they are equal)
var_dump($a !== $b); // true (types are different)

Logical Operators

Used in decision-making.

$loggedIn = true;
$hasPermission = false;

if ($loggedIn && $hasPermission) {
  echo "Welcome, admin!";
} else {
  echo "Access denied.";
}

Increment & Decrement Operators

These operators increase or decrease a variable’s value by 1.

$counter = 10;
$counter++; // Increments (Now 11)
$counter--; // Decrements (Back to 10)

String Operators

Concatenation (combining strings) is done using . (dot).

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

Ternary Operator 

A shorthand for if-else statements.

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

PHP operators are powerful tools that help manipulate data and control program flow.

Post a Comment

0 Comments