In PHP, operators are used to perform operations on variables and values. Operators allow you to perform various tasks like arithmetic, comparison, logical operations, and more. Understanding the different types of operators in PHP will help you manipulate and work with data effectively.
Arithmetic operators are used to perform basic mathematical operations.
<?php $a = 10; $b = 5; echo $a + $b; // Addition (15) echo $a - $b; // Subtraction (5) echo $a * $b; // Multiplication (50) echo $a / $b; // Division (2) echo $a % $b; // Modulus (0) echo $a ** $b; // Exponentiation (100000) ?>
Assignment operators are used to assign values to variables. These operators simplify value assignment.
<?php $x = 10; // Basic assignment $x += 5; // Addition assignment (x = x + 5) $x -= 3; // Subtraction assignment (x = x - 3) $x *= 2; // Multiplication assignment (x = x * 2) $x /= 4; // Division assignment (x = x / 4) echo $x; ?>
Comparison operators are used to compare two values. These operators return a boolean value (true or false).
<?php $x = 10; $y = 20; var_dump($x == $y); // Equal to var_dump($x != $y); // Not equal to var_dump($x > $y); // Greater than var_dump($x < $y); // Less than var_dump($x >= $y); // Greater than or equal to var_dump($x <= $y); // Less than or equal to ?>
Logical operators are used to perform logical operations, commonly used in `if` statements.
<?php $x = true; $y = false; var_dump($x && $y); // Logical AND (false) var_dump($x || $y); // Logical OR (true) var_dump(!$x); // Logical NOT (false) ?>
Increment and Decrement operators are used to increase or decrease a variable's value by 1.
<?php $x = 5; echo ++$x; // Pre-increment (6) echo $x++; // Post-increment (6, then 7) echo --$x; // Pre-decrement (6) echo $x--; // Post-decrement (6, then 5) ?>
String operators are used to combine or append strings.
<?php $str1 = "Hello "; $str2 = "World!"; echo $str1 . $str2; // Concatenation ("Hello World!") $str1 .= $str2; // Concatenation assignment echo $str1; // ("Hello World!") ?>
Array operators are used to compare arrays.
<?php $arr1 = array("a" => "apple", "b" => "banana"); $arr2 = array("a" => "apple", "c" => "cherry"); var_dump($arr1 + $arr2); // Union of arrays var_dump($arr1 == $arr2); // Arrays are equal? var_dump($arr1 === $arr2); // Arrays are identical? ?>
The ternary operator is a shorthand for an `if-else` statement.
<?php $x = 5; $result = ($x > 3) ? "Greater" : "Smaller"; echo $result; // Output: Greater ?>
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!