PHP Operators (With Examples)

By Shahnail Khan Last updated : December 7, 2023

PHP Operators

Operators are fundamental building blocks of programming languages. They allow us to manipulate and combine data to achieve desired results. In PHP, there are many operators available for various purposes. This tutorial will introduce you to the most common PHP operators and provide examples of their usage.

The following are the operators in PHP:

  1. Arithmetic Operators
  2. Assignment Operators
  3. Comparison Operators
  4. Increment/Decrement Operators
  5. Logical Operators
  6. String Operators
  7. Array Operators
  8. Conditional Assignment Operators

1) PHP Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, and division.

The following are the PHP arithmetic operators:

Operator Description Example
+ Addition $sum = 100 + 50; // $sum will be 150
- Subtraction $difference = 200 - 100; // $difference will be 100
* Multiplication $product = 5 * 3; // $product will be 15
/ Division $quotient = 100 / 2; // $quotient will be 50
% Modulus $remainder = 100 % 3; // $remainder will be 1

Example of PHP Arithmetic Operators

<?php
$sum = 100 + 50;
$difference = 200 - 100;
$product = 5 * 3;
$quotient = 100 / 2;
$remainder = 100 % 3;

// printing
echo $sum . "<br>";
echo $difference . "<br>";
echo $product . "<br>";
echo $quotient . "<br>";
echo $remainder . "<br>";
?>

The output of the above example is:

150
100
15
50
1

2) PHP Assignment Operators

Assignment operators are used to assign values to variables.

The following are the PHP assignment operators:

Operator Description Example
= Simple assignment $a = 65;
+= Adds and assigns $a += 5; means (a=a+5) // $a will be 70
-= Subtracts and assigns $a -= 5; means (a=a-5) // $a will be 65
*= Multiplies and assigns $a *= 2; means (a*2) // $a will be 130
/= Divides and assigns $a /= 2; // $a will be 10

Example of PHP Assignment Operators

<?php
$a = 65;
echo $a . "<br>";

$a += 5;
echo $a . "<br>";

$a -= 5;
echo $a . "<br>";

$a *= 2;
echo $a . "<br>";

$a /= 2;
echo $a . "<br>";
?>

The output of the above example is:

65
70
65
130
65

3) PHP Comparison Operators

Comparison operators are used to compare two values and return a Boolean (true/false) result.

The following are the PHP comparison operators:

Operator Description Example
== Equal to $a == 10; // true
!= Not equal to $a != 10; // false
< Less than $a < 10; // false
> Greater than $a > 10; // false
<= Less than or equal to $a <= 10; // true
>= Greater than or equal to $a >= 10; // true
<=> Spaceship operator (PHP 7+) $a <=> 10; // -1

Example of PHP Comparison Operators

<?php
$a = 10;

$result = $a == 10;
var_dump($result);
echo "<br>";

$result = $a != 10;
var_dump($result);
echo "<br>";

$result = $a < 10;
var_dump($result);
echo "<br>";

$result = $a > 10;
var_dump($result);
echo "<br>";

$result = $a <= 10;
var_dump($result);
echo "<br>";

$result = $a >= 10;
var_dump($result);
echo "<br>";

$result = $a <=> 10;
var_dump($result);
echo "<br>";
?>

The output of the above example is:

bool(true)
bool(false)
bool(false)
bool(false)
bool(true)
bool(true)
int(0)

4) PHP Increment/Decrement Operators

Increment and decrement operators are used to increase or decrease the value of a variable by 1.

The following are the PHP increment/decrement operators:

Operator Description Example
++ Pre-increment ++$a; // $a becomes 11
-- Pre-decrement --$a; // $a becomes 9
$a++ Post-increment $a++; // $a becomes 10 (after the statement execution)
$a-- Post-decrement $a--; // $a becomes 9 (after the statement execution)

Example of PHP Increment/Decrement Operators

<?php
$a = 10;

++$a;
echo $a . "<br>";

--$a;
echo $a . "<br>";

$a++;
echo $a . "<br>";

$a--;
echo $a . "<br>";
?>

The output of the above example is:

11
10
11
10

5) PHP Logical Operators

Logical operators are used to combine two or more Boolean values and return a single Boolean result.

The following are the PHP logical operators:

Operator Description Example
&& Logical And $a > 10 && $b < 5; // true only if both $a > 10 and $b < 5 are true
|| Logical Or $a and $b; // Return true if both are true
! Logical Not !($a > 10); // true if $a is not greater than 10
and Logical And $a and $b; // Return true if both are true
or Logical Or $a or $b; // Return true if either is true
xor Logical Xor $a xor $b; // Return true if either is true, but not both

Example of PHP Logical Operators

<?php
$a = 10;
$b = 5;

$result = $a == 10 && $b == 5;
var_dump($result);
echo "<br>";

$result = $a == 10 || $b == 5;
var_dump($result);
echo "<br>";

$result = !($a == 10 && $b == 5);
var_dump($result);
echo "<br>";

$result = ($a == 10 and $b == 5);
var_dump($result);
echo "<br>";

$result = ($a == 10 or $b == 5);
var_dump($result);
echo "<br>";

$result = ($a == 10 xor $b == 5);
var_dump($result);
echo "<br>";
?>

The output of the above example is:

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

6) PHP String Operators

String operators are used to manipulate and combine strings.

The following are the PHP string operators:

Operator Description Example
. Concatenation $str1 = "Include" . " " . $str2;
.= String concatenation and assignment $str1 .= "Help";
== Equal to $str1 == "Include Help"; // true
!= Not equal to $str1 != "Include Help"; // false

Example of PHP String Operators

<?php
$str1 = "Include";
$str2 = "Help";

$result = $str1 . $str2;
echo $result . "<br>";

$result .= $str1;
echo $result . "<br>";

$result = $str1 == $str2;
var_dump($result);
echo "<br>";

$result = $str1 != $str2;
var_dump($result);
echo "<br>";
?>

The output of the above example is:

IncludeHelp
IncludeHelpInclude
bool(false)
bool(true)

7) PHP Array Operators

Array operators in PHP are used to compare two arrays, these are basically a kind of relation operators for the array companions.

The following are the PHP array operators:

Operator Description Example
+ Array Union $a + $b; - Returns union or arrays.
== Array Equality $a == $b; - Returns if both have the same key and value pairs.
=== Array Identity $a == $b; - Returns if both have the same key and value pairs (their order and type must be same).
!= Array Inequality $a != $b; - Returns true if both are not equal.
<> Array Inequality $a <> $b; - Returns true if both are not equal.
!== Array non-identity $a <> $b; - Returns true if $a is not identical to $b.

Example of PHP Array Operators

<?php
$x = ["fruit" => "Apple", "color" => "Red"];
$y = ["company" => "Honda", "model" => "City"];

print_r($x + $y);
echo "<br>";

var_dump($x == $y);
echo "<br>";

var_dump($x === $y);
echo "<br>";

var_dump($x != $y);
echo "<br>";

var_dump($x != $y);
echo "<br>";

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

The output of the above example is:

Array ( [fruit] => Apple [color] => Red [company] => Honda [model] => City )
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)

8) PHP Conditional Assignment Operators

Conditional assignment operators are used to define value based on the given conditions.

The following are the PHP conditional assignment operators:

Operator Description Example
?: Ternary Operator $result = expr1 ? expr2 : expr2;
?? Non-Coalescing Operator $result = expr1 ?? expr2;

Example of PHP Conditional Assignment Operators

<?php
$a = 10;
$b = 5;
$result = $a > $b ? $a : $b;
echo "Largest value is " . $result . "<br>";

// Assigns "Hello, world!",
// if $welcome either not defined or null
$welcome = $welcome ?? "Hello, world!";
echo "Welcome message is " . $welcome . "<br>";
?>

The output of the above example is:

Largest value is 10
Welcome message is Hello, world!

PHP Operators Practice (More Examples)

Now let's practice some questions to understand PHP Operators better.

To understand the below-given examples/practices, you should have the knowledge of the following PHP topics:

Exercise 1

Write a PHP script that calculates the area of a rectangle given its length and width using arithmetic operators.

<?php
// Calculate the area of a rectangle
$length = 5;
$width = 8;
$area = $length * $width;
echo "The area of the rectangle is: $area";
?>

The output of the above example is:

The area of the rectangle is: 40

Exercise 2

Create a PHP script that checks if a given number is both divisible by 2 and 3. Use logical operators to perform the check.

<?php
// Check if a number is divisible by 2 and 3
$number = 12;
if ($number % 2 == 0 && $number % 3 == 0) {
    echo "$number is divisible by both 2 and 3.";
} else {
    echo "$number is not divisible by both 2 and 3.";
}
?>

The output of the above example is:

12 is divisible by both 2 and 3.

Exercise 3

Write a PHP function that compares two strings and returns "Equal" if they are the same, "Greater" if the first string is lexicographically greater, and "Smaller" if the second string is lexicographically greater.

<?php
// Compare two strings
function compareStrings($str1, $str2)
{
    $result = strcmp($str1, $str2);
    if ($result == 0) {
        return "Equal";
    } elseif ($result > 0) {
        return "Greater";
    } else {
        return "Smaller";
    }
}
echo compareStrings("apple", "orange");
?>

The output of the above example is:

Smaller

Exercise 4

Implement a PHP script that determines whether a given number is positive, negative, or zero using the ternary operator.

<?php
// Determine if a number is positive, negative, or zero
$number = -7;
$result = $number > 0 ? "Positive" : ($number < 0 ? "Negative" : "Zero");
echo "The number is $result.";
?>

The output of the above example is:

The number is Negative.

Exercise 5

Develop a PHP program that uses the multiplication and assignment operator (*=) to calculate the square of a number.

<?php
// Calculate the square of a number using *=
$number = 4;
$number *= $number;
echo "The square of the number is: $number";
?>

The output of the above example is:

The square of the number is: 16

Exercise 6

Write a PHP function that takes two numbers as parameters and uses the spaceship operator to return:

  • -1 if the first number is less than the second,
  • 0 if they are equal,
  • 1 if the first number is greater than the second.
<?php
// Use spaceship operator to compare two numbers
function compareNumbers($num1, $num2)
{
    return $num1 <=> $num2;
}
$result = compareNumbers(8, 5);
echo "Result: $result";
?>

The output of the above example is:

Result: 1

Exercise 7

Create an array of fruits and another array of vegetables. Use array operators to merge these arrays and display the combined list.

<?php
// Merge arrays of fruits and vegetables
$fruits = ["apple", "banana", "orange"];
$vegetables = ["carrot", "broccoli", "spinach"];

$combined = $fruits + $vegetables;

print_r($combined);
?>

The output of the above example is:

Array ( [0] => apple [1] => banana [2] => orange )

Exercise 8

Implement a PHP script that uses a loop to print the numbers from 1 to 10 using the post-increment operator.

<?php
// Print numbers from 1 to 10 using post-increment operator
$i = 1;
while ($i <= 10) {
    echo "$i ";
    $i++;
}
?>

The output of the above example is:

1 2 3 4 5 6 7 8 9 10

Exercise 9

Write a PHP function that takes two strings as parameters and concatenates them using the concatenation and assignment operator (.=). Return the resulting string.

<?php
// Concatenate two strings using .=
function concatenateStrings($str1, $str2)
{
    $str1 .= $str2;
    return $str1;
}
echo concatenateStrings("Hello", " World!");
?>

The output of the above example is:

Hello World!

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.