What is PHP Operators?
In PHP, operators are symbols or special keywords used to perform various operations on variables, constants, and values. PHP supports a wide range of operators that can be categorized into different groups based on their functionality. Below, I’ll provide details on the most common types of operators in PHP:
Let’s go through various PHP operators with examples:
- Arithmetic Operators:
$a = 10;
$b = 3;
$addition = $a + $b; // 10 + 3 = 13
$subtraction = $a - $b; // 10 - 3 = 7
$multiplication = $a * $b; // 10 * 3 = 30
$division = $a / $b; // 10 / 3 = 3.333...
$modulo = $a % $b; // 10 % 3 = 1
$increment = ++$a; // Pre-increment: $a becomes 11
$decrement = $b--; // Post-decrement: $b becomes 2, but $decrement is 3
- Assignment Operators:
$c = 5;
$d = 7;
$c += $d; // Equivalent to $c = $c + $d; $c becomes 12
$d -= $c; // Equivalent to $d = $d - $c; $d becomes -5
- Comparison Operators:
$e = 10;
$f = "10";
var_dump($e == $f); // true (Loose comparison, values are the same)
var_dump($e === $f); // false (Strict comparison, values are the same but types are different)
var_dump($e != $f); // false (Loose comparison, values are the same)
var_dump($e !== $f); // true (Strict comparison, values are the same but types are different)
var_dump($e > $f); // false (10 is not greater than 10)
var_dump($e < $f); // false (10 is not less than 10)
var_dump($e >= $f); // true (10 is equal to 10)
var_dump($e <= $f); // true (10 is equal to 10)
- Logical Operators:
$g = true;
$h = false;
$logicalAnd = $g && $h; // false
$logicalOr = $g || $h; // true
$logicalNot = !$g; // false
- String Operators:
$string1 = "Hello";
$string2 = " World";
$concatenatedString = $string1 . $string2; // "Hello World"
- Array Operators:
$array1 = array("a" => 1, "b" => 2);
$array2 = array("b" => 3, "c" => 4);
$unionArray = $array1 + $array2; // array("a" => 1, "b" => 2, "c" => 4)
$equalityCheck = $array1 == $array2; // false (different values)
$identityCheck = $array1 === $array2; // false (different keys and values)
- Ternary Operator:
$age = 25;
$canVote = ($age >= 18) ? "Yes" : "No";
// Since $age is greater than or equal to 18, $canVote becomes "Yes"
- Null Coalescing Operator (since PHP 7):
$username = $_GET['username'] ?? "Guest";
// If $_GET['username'] is set, $username will have its value, otherwise, "Guest"
- Type Operators (instanceof):
class Animal {}
class Dog extends Animal {}
$animal = new Dog();
var_dump($animal instanceof Animal); // true (Dog is an instance of Animal class)
var_dump($animal instanceof Dog); // true (Dog is an instance of Dog class)
These examples demonstrate the usage of various PHP operators and their functionalities in different scenarios. Operators are essential tools for performing calculations, comparisons, and making decisions in PHP programming.