Category: Basic

  • Spaceship Operator

    The Spaceship operator is one of the many new features introduced in PHP with its 7.0 version. It is a three-way comparison operator.

    The conventional comparison operators (<, >, !=, ==, etc.) return true or false (equivalent to 1 or 0). On the other hand, the spaceship operator has three possible return values: -1,0,or 1. This operator can be used with integers, floats, strings, arrays, objects, etc.

    Syntax of the Spaceship Operator

    The symbol used for spaceship operator is “<=>”.

    $retval= operand1 <=> operand2
    

    Here, $retval is -1 if operand1 is less than operand2, 0 if both the operands are equal, and 1 if operand1 is greater than operand2.

    The spaceship operator is implemented as a combined comparison operator. Conventional comparison operators could be considered mere shorthands for <=> as the following table shows −

    Operator<=> equivalent
    $a < $b($a <=> $b) === -1
    $a <= $b($a <=> $b) === -1 || ($a <=> $b) === 0
    $a == $b($a <=> $b) === 0
    $a != $b($a <=> $b) !== 0
    $a >= $b($a <=> $b) === 1 || ($a <=> $b) === 0
    $a > $b($a <=> $b) === 1

    Example 1

    The following example shows how you can use the spaceship operator in PHP. We will compare 5 with 10/2. As both values are equal so the result will be 0 −

    <?php
       $x = 5;
       $y = 10;
       $z = $x <=> $y/2;
    
       echo "$x <=> $y/2 = $z";
    ?>

    Output

    It will create the following output −

    5 <=> 10/2 = 0
    

    Example 2

    Now we change $x=4 and check the result. As 4 is less than 10/2 so the spaceship operator will return -1 −

    <?php
       $x = 4;
       $y = 10;
       $z = $x <=> $y/2;
    
       echo "$x <=> $y/2 = $z";
    ?>

    Output

    It will produce the following output −

    4 <=> 10/2 = -1
    

    Example 3

    Now let us change $y=7 and check the result again. Now 7 is greater than 10/2 so the spaceship operator will return 1 −

    <?php
       $x = 7;
       $y = 10;
       $z = $x <=> $y/2;
    
       echo "$x <=> $y/2 = $z";
    ?>

    Output

    It will produce the following result −

    7 <=> 10/2 = 1
    

    Example 4

    The spaceship operator, like the strcmp() method, works on strings. In this program, we will compare the phrases “bat” and “ball”. Since “bat” comes after “ball” in alphabetical order so the result is 1.

    <?php
       $x = "bat";
       $y = "ball";
       $z = $x <=> $y;
    
       echo "$x <=> $y = $z";
    ?>

    Output

    It will generate the following outcome −

    bat <=> ball = 1
    

    Example 5

    Change $y = “baz” and check the result −

    <?php
       $x = "bat";
       $y = "baz";
       $z = $x <=> $y;
    
       echo "$x <=> $y = $z";
    ?>

    Output

    It will produce the below output −

    bat <=> baz = -1
    

    Spaceship Operator with Boolean Operands

    The spaceship operator also works with Boolean operands −

    true<=>false returns 1false<=>true returns -1true<=>trueas well asfalse<=>false returns 0

  • Null Coalescing Operator

    The Null Coalescing operator is one of the many new features introduced in PHP 7. The word “coalescing” means uniting many things into one. This operator is used to replace the ternary operation in conjunction with the isset() function.

    Ternary Operator in PHP

    PHP has a ternary operator represented by the “?” symbol. The ternary operator compares a Boolean expression and executes the first operand if it is true, otherwise it executes the second operand.

    Syntax

    Here is the syntax for using the ternary operator −

    expr ? statement1 : statement2;

    Example: Variable is Set

    Let us use the ternary operator to check if a certain variable is set or not with the help of the isset() function, which returns true if declared and false if not.

    <?php
       $x = 1;
       $var = isset($x) ? $x : "not set";
       echo "The value of x is $var";
    ?>

    It will produce the following output −

    The value of x is 1
    

    Example: Variable is Not Set

    Now, let’s remove the declaration of “x” and rerun the code −

    <?php
       # $x = 1;
       $var = isset($x) ? $x : "not set";
       echo "The value of x is $var";
    ?>

    The code will now produce the following output −

    The value of x is not set
    

    The Null Coalescing Operator

    The Null Coalescing Operator is represented by the “??” symbol. It acts as a convenient shortcut to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null; otherwise it returns its second operand.

    Syntax

    Below is the syntax for using the null coalescing operator −

    $Var=$operand1??$operand2;

    The first operand checks whether a certain variable is null or not (or is set or not). If it is not null, the first operand is returned, else the second operand is returned.

    Example: Variable is Not Set

    Take a look at the following example −

    <?php
       # $num = 10;
       $val = $num ?? 0;
       echo "The number is $val";
    ?>

    It will produce the following output −

    The number is 0
    

    Example: Variable is Set

    Now uncomment the first statement that sets $num to 10 and rerun the code −

    <?php
       $num = 10;
       $val = $num ?? 0;
       echo "The number is $val";
    ?>

    It will now produce the following output −

    The number is 10
    

    A useful application of Null Coalescing operator is while checking whether a username has been provided by the client browser.

    Checking for a Username in URL

    The following code reads the name variable from the URL. If indeed there is a value for the name parameter in the URL, a Welcome message for him is displayed. However, if not, the user is called Guest.

    <?php
       $username = $_GET['name'] ?? 'Guest';
       echo "Welcome $username";
    ?>

    Assuming that this script “hello.php” is in the htdocs folder of the PHP server, enter http://localhost/hello.php?name=Amar in the URL, the browser will show the following message −

    Welcome Amar
    

    If http://localhost/hello.php is the URL, the browser will show the following message −

    Welcome Guest
    

    Using isset() and Ternary Operator

    The Null coalescing operator is used as a replacement for the ternary operators specific case of checking isset() function. Hence, the following statements give similar results −

    <?php
       $username = isset($_GET['name']) ? $_GET['name'] : 'Guest';
       echo "Welcome $username";
    ?>

    It will now produce the following output −

    Welcome Guest
    

    Chaining Null Coalescing Operator (??)

    You can chain the “??” operators as shown below −

    <?php
       $username = $_GET['name'] ?? $_POST['name'] ?? 'Guest';
       echo "Welcome $username";
    ?>

    It will now produce the following output −

    Welcome Guest
    

    This will set the username to Guest if the variable $name is not set either by GET or by POST method.

  • Spread Operator

    PHP recognizes the three dots symbol (…) as the spread operator. The spread operator is also sometimes called the splat operator. This operator was first introduced in PHP version 7.4. It can be effectively used in many cases such as unpacking arrays.

    The spread operator increases the readability of arrays and function parameters. It is a simple but useful feature for modern PHP development.

    So here is the list concepts with example, we will cover in this chapter −

    • Syntax of PHP Spread Operator
    • Expanding an Array with Spread Operator
    • Using Spread Operator Multiple Times
    • Spread Operator vs array_merge()
    • Named Arguments with Spread Operator
    • Using Spread Operator with Function Return Value

    Syntax

    Below is the syntax of the PHP spread operator −

    // Expanding an array$newArray=[...$existingArray];// Using in a functionfunctionmyFunction(...$args){// Function body}

    Expanding an Array with Spread Operator

    In the example below, the elements in $arr1 are inserted in $arr2 after a list of its own elements.

    <?php
       $arr1 = [4,5];
       $arr2 = [1,2,3, ...$arr1];
    
       print_r($arr2);
    ?>

    Output

    This will produce the following result −

    Array
    (
       [0] => 1
       [1] => 2
       [2] => 3
       [3] => 4
       [4] => 5
    )
    

    Using Spread Operator Multiple Times

    The Spread operator can be used more than once in an expression. For example, in the following code, a third array is created by expanding the elements of two arrays.

    <?php
       $arr1 = [1,2,3];
       $arr2 = [4,5,6];
       $arr3 = [...$arr1, ...$arr2];
    
       print_r($arr3);
    ?>

    Output

    This will generate the below result −

    Array
    (
       [0] => 1
       [1] => 2
       [2] => 3
       [3] => 4
       [4] => 5
       [5] => 6
    )
    

    Spread Operator vs array_merge()

    Note that the same result can be obtained with the use of array_merge() function, as shown below −

    <?php
       $arr1 = [1,2,3];
       $arr2 = [4,5,6];
       $arr3 = array_merge($arr1, $arr2);
    
       print_r($arr3);
    ?>

    Output

    This will create the below outcome −

    Array
    (
       [0] => 1
       [1] => 2
       [2] => 3
       [3] => 4
       [4] => 5
       [5] => 6
    )
    

    However, the use of (…) operator is much more efficient as it avoids the overhead a function call.

    Named Arguments with Spread Operator

    PHP 8.1.0 also introduced another feature that allows using named arguments after unpacking the arguments. Instead of providing a value to each of the arguments individually, the values from an array will be unpacked into the corresponding arguments, using … (three dots) before the array.

    <?php  
       function  myfunction($x, $y, $z=30) {
    
      echo "x = $x  y = $y  z = $z";
    } myfunction(...[10, 20], z:30); ?>

    Output

    This will lead to the following outcome −

    x = 10  y = 20  z = 30
    

    Using Spread Operator with Function Return Value

    In the following example, the return value of a function is an array. The array elements are then spread and unpacked.

    <?php
       function get_squares() {
    
      for ($i = 0; $i &lt; 5; $i++) {
         $arr[] = $i**2;
      }
      return $arr;
    } $squares = [...get_squares()]; print_r($squares); ?>

    Output

    The result of this PHP code is −

    Array
    (
       [0] => 0
       [1] => 1
       [2] => 4
       [3] => 9
       [4] => 16
    )
    
  • Conditional Operators 

    You would use conditional operators in PHP when there is a need to set a value depending on conditions. It is also known as ternary operator. It first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation.

    Ternary operators offer a concise way to write conditional expressions. They consist of three parts: the condition, the value to be returned if the condition evaluates to true, and the value to be returned if the condition evaluates to false.

    OperatorDescriptionExample
    ? :Conditional ExpressionIf Condition is true ? Then value X : Otherwise value Y

    Syntax of the Conditional Operator

    The syntax to use the conditional operator is as follows −

    condition ? value_if_true : value_if_false
    

    Ternary operators are especially useful for shortening if-else statements into a single line. You can use a ternary operator to assign different values to a variable based on a condition without needing multiple lines of code. It can improve the readability of the code.

    However, you should use ternary operators judiciously, else you will end up making the code too complex for others to understand.

    Example – Basic Usage of Conditional Operator

    Try the following example to understand how the conditional operator works in PHP. Copy and paste the following PHP program in test.php file and keep it in your PHP Server’s document root and browse it using any browser.

    <?php
       $a = 10;
       $b = 20;
    
       /* If condition is true then assign a to result otherwise b */
       $result = ($a > $b ) ? $a :$b;
    
       echo "TEST1 : Value of result is $result \n";
    
       /* If condition is true then assign a to result otherwise b */
       $result = ($a < $b ) ? $a :$b;
    
       echo "TEST2 : Value of result is $result";
    ?>

    Output

    It will produce the following output −

    TEST1 : Value of result is 20
    TEST2 : Value of result is 10
    

    Example: Check Even or Odd Number

    Here we will use the conditional operator to check the even and odd numbers. And print the result as per the condition.

    <?php
       $num = 15;
       $result = ($num % 2 == 0) ? "Even" : "Odd";
       echo "Number $num is $result";
    ?>

    Output

    This will generate the below output −

    Number 15 is Odd
    

    Example 2: Check Positive, Negative or Zero

    Now the below code checks the positive, negative and zero values by using the nested conditional operator. See the code below −

    <?php
       $num = -5;
       $result = ($num > 0) ? "Positive" : (($num < 0) ? "Negative" : "Zero");
       echo "Number $num is $result";
    ?>

    Output

    This will create the below output −

    Number -5 is Negative
    

    Example 3: Find the Maximum of Three Numbers

    In the following example, we are showing that you can use the conditional operator for finding the maximum of three different numbers. See the example below −

    <?php
       $x = 50;
       $y = 30;
       $z = 80;
    
       $max = ($x > $y) ? (($x > $z) ? $x : $z) : (($y > $z) ? $y : $z);
    
       echo "The maximum number is $max";
    ?>

    Output

    Following is the output of the above code −

    The maximum number is 80

  • Array Operators

    In PHP, array operators are used to compare and combine arrays. These operators are useful for a variety of tasks, like merging two arrays, testing if two arrays are equal and finding whether they have the same order and data types.

    PHP defines the following set of symbols to be used as operators on array data types −

    NameSymbolExampleResult
    Union+$a + $bUnion of $a and $b.
    Equality==$a == $bTRUE if $a and $b have the same key/value pairs.
    Identity===$a === $bTRUE if $a and $b have the same key/value pairs in the same order and of the same types.
    Inequality!=$a != $bTRUE if $a is not equal to $b.
    Inequality<>$a <> $bTRUE if $a is not equal to $b.
    Non identity!==$a !== $bTRUE if $a is not identical to $b.

    Example: Union Operator in PHP

    The Union operator appends the right-hand array appended to left-hand array. If a key exists in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

    The following example shows how you can use the union operator in PHP −

    <?php
       $arr1=array("phy"=>70, "che"=>80, "math"=>90);
       $arr2=array("Eng"=>70, "Bio"=>80,"CompSci"=>90);
       $arr3=$arr1+$arr2;
       var_dump($arr3);
    ?>

    Output

    It will generate the following result −

    array(6) {
       ["phy"]=>
       int(70)
       ["che"]=>
       int(80)
       ["math"]=>
       int(90)
       ["Eng"]=>
       int(70)
       ["Bio"]=>
       int(80)
       ["CompSci"]=>
       int(90)
    }
    

    Example: When Two Array are Equal

    Two arrays are said to be equal if they have the same key-value pairs.

    In the following example, we have an indexed array and other associative array with keys corresponding to index of elements in first. Hence, both are equal.

    <?php
       $arr1=array(0=>70, 2=>80, 1=>90);
       $arr2=array(70,90,80);
       var_dump ($arr1==$arr2);
       var_dump ($arr2!=$arr1);
    ?>

    Output

    It will produce the following output −

    bool(true)
    bool(false)
    

    Example: When Two Arrays are Identical

    Arrays are identical if and only if both of them have same set of key-value pairs and in same order.

    <?php
       $arr1=array(0=>70, 1=>80, 2=>90);
       $arr2=array(70,90,80);
       var_dump ($arr1===$arr2);
       $arr3=[70,80,90];
       var_dump ($arr3===$arr1);
    ?>

    Output

    This will create the below outcome −

    bool(false)
    bool(true)
    

    Example: Using Inequality (!=) Operator

    The != operator is used to check that two arrays are not equal. So it returns true if the arrays have different key-value pairs and false if have same key-value pairs.

    <?php
       $arr1 = array("a" => 1, "b" => 2, "c" => 3);
       $arr2 = array("a" => 1, "b" => 5, "c" => 3);
       $arr3 = array("a" => 1, "b" => 2, "c" => 3);
    
       // Checking if $arr1 and $arr2 are not equal
       var_dump($arr1 != $arr2); 
    
       // Checking if $arr1 and $arr3 are not equal
       var_dump($arr1 != $arr3);
    ?>

    Output

    This will produce the output given below −

    bool(true)  
    bool(false) 
    

    Example: Using Non-Identity (!==) Operator

    You may know that Non-Identity (!==) operator is used to check if two arrays are not identical. So in our example we will check if the return value is true so the arrays are not identical.

    <?php
       $arr1 = array(0 => 70, 1 => "80", 2 => 90); 
       $arr2 = array(0 => 70, 1 => 80, 2 => 90);   
    
       var_dump($arr1 !== $arr2); 
    
       $arr3 = array(0 => 70, 2 => 90, 1 => 80);
    
       var_dump($arr1 !== $arr3);
    ?>

    Output

    This will generate the below output −

    bool(true)
    bool(true)
    

    Example: Using Inequality (<>) Operator

    Inequality (<>) Operator works the same as ‘!=’ does but it is good to explicitly see how it works.

    <?php
       $arr1 = array("a" => 10, "b" => 20);
       $arr2 = array("a" => 10, "b" => 25);
    
       var_dump($arr1 <> $arr2); 
    ?>

    Output

    This will produce the below outcome −

    bool(true)

  • String Operators

    There are two operators in PHP for working with string data types: concatenation operator (“.”) and the concatenation assignment operator (“.=”). Read this chapter to learn how these operators work in PHP.

    Concatenation Operator in PHP

    The dot operator (“.”) is PHP’s concatenation operator. It joins two string operands (characters of right hand string appended to left hand string) and returns a new string.

    $third=$first.$second;

    Example

    The following example shows how you can use the concatenation operator in PHP −

    <?php
       $x="Hello";
       $y=" ";
       $z="PHP";
       $str=$x . $y . $z;
       echo $str;
    ?>

    Output

    It will produce the following output −

    Hello PHP
    

    Concatenation Assignment Operator in PHP

    PHP also has the “.=” operator which can be termed as the concatenation assignment operator. It updates the string on its left by appending the characters of right hand operand.

    $leftstring.=$rightstring;

    Example

    The following example uses the concatenation assignment operator. Two string operands are concatenated returning the updated contents of string on the left side −

    <?php
       $x="Hello ";
       $y="PHP";
       $x .= $y;
       echo $x;
    ?>

    Output

    It will produce the following result −

    Hello PHP
    

    Working with Variables and Strings

    In the below PHP code we will try to work with variables and strings. So you may know that you can also concatenate strings with variables in PHP. Here two variables are combined with other strings to create a sentence −

    <?php
       $name = "Ankit";
       $age = 25;
       $sentence = "My name is " . $name . " and I am " . $age . " years old.";
       echo $sentence;
    ?>

    Output

    This will generate the below output −

    My name is Ankit and I am 25 years old.
    

    Using Concatenation in Loops

    Now the below code demonstrate how concatenation can be used inside loops to create a long string. See the example below −

    <?php
       $result = "";
       for ($i = 1; $i <= 5; $i++) {
    
      $result .= "Number " . $i . "\n";
    } echo $result; ?>

    Output

    This will create the below output −

    Number 1
    Number 2
    Number 3
    Number 4
    Number 5
    

    Combining Strings with Different Data Types

    In the following example, we are showing how you can combine different data types with strings and show the output −

    <?php
       $price = 100;
       $message = "The price is " . $price . " rupees.";
       echo $message;
    ?>

    Output

    Following is the output of the above code −

    The price is 100 rupees.

  • Assignment Operators

    You can use assignment operators in PHP to assign values to variables. Assignment operators are shorthand notations to perform arithmetic or other operations while assigning a value to a variable. For instance, the “=” operator assigns the value on the right-hand side to the variable on the left-hand side.

    Additionally, there are compound assignment operators like +=, -= , *=, /=, and %= which combine arithmetic operations with assignment. For example, “$x += 5” is a shorthand for “$x = $x + 5”, incrementing the value of $x by 5. Assignment operators offer a concise way to update variables based on their current values.

    Assignment Operators List

    The following table highlights the assignment operators that are supported by PHP −

    OperatorDescriptionExample
    =Simple assignment operator. Assigns values from right side operands to left side operandC = A + B will assign value of A + B into C
    +=Add AND assignment operator. It adds right operand to the left operand and assign the result to left operandC += A is equivalent to C = C + A
    -=Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operandC -= A is equivalent to C = C – A
    *=Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operandC *= A is equivalent to C = C * A
    /=Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operandC /= A is equivalent to C = C / A
    %=Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operandC %= A is equivalent to C = C % A

    Example

    The following example shows how you can use these assignment operators in PHP −

    <?php
       $a = 42;
       $b = 20;
    
       $c = $a + $b;
       echo "Addition Operation Result: $c \n";
    
       $c += $a;
       echo "Add AND Assignment Operation Result: $c \n";
    
       $c -= $a;
       echo "Subtract AND Assignment Operation Result: $c \n";
    
       $c *= $a;
       echo "Multiply AND Assignment Operation Result: $c \n";
    
       $c /= $a;
       echo "Division AND Assignment Operation Result: $c \n";
    
       $c %= $a;
       echo "Modulus AND Assignment Operation Result: $c";
    ?>

    Output

    It will produce the following outcome −

    Addition Operation Result: 62 
    Add AND Assignment Operation Result: 104 
    Subtract AND Assignment Operation Result: 62 
    Multiply AND Assignment Operation Result: 2604 
    Division AND Assignment Operation Result: 62 
    Modulus AND Assignment Operation Result: 20
    

    Bitwise Assignment Operators

    PHP also has bitwise assignment operators, which let you perform bitwise operations and store the result in the same variable. Please refer to the below table for the list of bitwise assignment operators −

    OperatorDescriptionExample
    =Simple assignment operator. Assigns values from right side operands to left side operandC = A + B will assign value of A + B into C
    &=Bitwise AND assignment$a &= $b; // $a = $a & $b
    |=Bitwise OR assignment$a |= $b; // $a = $a | $b
    ^=Bitwise XOR assignment$a ^= $b; // $a = $a ^ $b
    <<=Left shift AND assignment$a <<= 2; // $a = $a << 2
    >>=Right shift AND assignment$a >>= 2; // $a = $a >> 2

    Use of Assignment Operators in Loops

    Here is an example of how assignment operators are used in loops can help understand the practical uses −

    <?php
       $num = 1;
       while ($num <= 10) {
    
      echo "$num ";
      // Increment by 2
      $num += 2; 
    } ?>

    Output

    This will generate the following result −

    1 3 5 7 9
    

  • Logical Operators

    In PHP, logical operators are used to combine conditional statements. These operators allow you to create more complex conditions by combining multiple conditions together.

    Logical operators are generally used in conditional statements such as if, while, and for loops to control the flow of program execution based on specific conditions.

    The following table highlights the logical operators that are supported by PHP.

    Assume variable $a holds 10 and variable $b holds 20, then −

    OperatorDescriptionExample
    andCalled Logical AND operator. If both the operands are true then condition becomes true.(A and B) is true
    orCalled Logical OR Operator. If any of the two operands are non zero then condition becomes true.(A or B) is true
    &&Called Logical AND operator. The AND operator returns true if both the left and right operands are true.(A && B) is true
    ||Called Logical OR Operator. If any of the two operands are non zero then condition becomes true.(A || B) is true
    !Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(A && B) is false

    Basic Usage of Logical Operators

    The following example shows how you can use these logical operators in PHP −

    <?php
       $a = 42;
       $b = 0;
    
       if ($a && $b) {
    
      echo "TEST1 : Both a and b are true \n";
    } else {
      echo "TEST1 : Either a or b is false \n";
    } if ($a and $b) {
      echo "TEST2 : Both a and b are true \n";
    } else {
      echo "TEST2 : Either a or b is false \n";
    } if ($a || $b) {
      echo "TEST3 : Either a or b is true \n";
    } else {
      echo "TEST3 : Both a and b are false \n";
    } if ($a or $b) {
      echo "TEST4 : Either a or b is true \n";
    } else {
      echo "TEST4 : Both a and b are false \n";
    } $a = 10; $b = 20; if ($a) {
      echo "TEST5 : a is true \n";
    } else {
      echo "TEST5 : a is false \n";
    } if ($b) {
      echo "TEST6 : b is true \n";
    } else {
      echo "TEST6 : b is false \n";
    } if (!$a) {
      echo "TEST7 : a is true \n";
    } else {
      echo "TEST7 : a is false \n";
    } if (!$b) {
      echo "TEST8 : b is true \n";
    } else {
      echo "TEST8 : b is false";
    } ?>

    Output

    It will produce the following output −

    TEST1 : Either a or b is false 
    TEST2 : Either a or b is false 
    TEST3 : Either a or b is true 
    TEST4 : Either a or b is true 
    TEST5 : a is true 
    TEST6 : b is true 
    TEST7 : a is false 
    TEST8 : b is false
    

    Using AND (&&) and OR (||) with User Input

    In the below PHP code example we will check if a user is eligible for a discount as per the age and membership status.

    <?php
       $age = 25;
       $isMember = true;
    
       if ($age > 18 && $isMember) {
    
      echo "You are eligible for a discount!\n";
    } else {
      echo "Sorry, you are not eligible for a discount.\n";
    } if ($age < 18 || !$isMember) {
      echo "You need to be at least 18 years old or a member to get a discount.";
    } ?>

    Output

    This will generate the below output −

    You are eligible for a discount!
    

    Check Multiple Conditions with And and Or

    Now the below code we will shows that the And and Or keywords work similarly like && and ||, but with lower precedence.

    <?php
       $x = 10;
       $y = 5;
    
       if ($x > 5 and $y < 10) {
    
      echo "Both conditions are true.\n";
    } if ($x == 10 or $y == 20) {
      echo "At least one condition is true.\n";
    } ?>

    Output

    This will create the below output −

    Both conditions are true.
    At least one condition is true.
    

    Using Logical Operators in a Loop

    In the following example, we are using logical operators in a while loop to control the flow.

    <?php
       $count = 1;
    
       while ($count <= 5 && $count != 3) {
    
      echo "Current count: $count\n";
      $count++;
    } ?>

    Output

    Following is the output of the above code −

    Current count: 1
    Current count: 2

  • Comparison Operators

    In PHP, Comparison operators are used to compare two values and determine their relationship. These operators return a Boolean value, either True or False, based on the result of the comparison.

    The following table highlights the comparison operators that are supported by PHP. Assume variable $a holds 10 and variable $b holds 20, then −

    OperatorDescriptionExample
    ==Checks if the value of two operands are equal or not, if yes then condition becomes true.($a == $b) is not true
    !=Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.($a != $b) is true
    >Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.($a > $b) is false
    <Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.($a < $b) is true
    >=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.($a >= $b) is false
    <=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.($a <= $b) is true

    Additionally, these operators can also be combined with logical operators (&&, ||, !) to form complex conditions for decision making in PHP programs.

    Basic Usage of Comparison Operators

    The following example shows how you can use these comparison operators in PHP −

    <?php
       $a = 42;
       $b = 20;
    
       if ($a == $b) {
    
      echo "TEST1 : a is equal to b \n";
    } else {
      echo "TEST1 : a is not equal to b \n";
    } if ($a > $b) {
      echo "TEST2 : a is greater than  b \n";
    } else {
      echo "TEST2 : a is not greater than b \n";
    } if ($a < $b) {
      echo "TEST3 : a is less than  b \n";
    } else {
      echo "TEST3 : a is not less than b \n";
    } if ($a != $b) {
      echo "TEST4 : a is not equal to b \n";
    } else {
      echo "TEST4 : a is equal to b \n";
    } if ($a >= $b) {
      echo "TEST5 : a is either greater than or equal to b \n";
    } else {
      echo "TEST5 : a is neither greater than nor equal to b \n";
    } if ($a <= $b) {
      echo "TEST6 : a is either less than or equal to b \n";
    } else {
      echo "TEST6 : a is neither less than nor equal to b";
    } ?>

    Output

    It will produce the following output −

    TEST1 : a is not equal to b
    TEST2 : a is greater than b
    TEST3 : a is not less than b
    TEST4 : a is not equal to b
    TEST5 : a is either greater than or equal to b
    TEST6 : a is neither less than nor equal to b
    

    PHP Equality (==) vs Identity (===) Operators

    In the below PHP code we will try to compare two variables. One variable is a number and the other variable is text. So it checks if both have the same value (==). Next it checks if both value and type are the same (===).

    <?php
       $x = 15;
       $y = "15";
    
       if ($x == $y) {
    
      echo "x is equal to y \n";
    } if ($x === $y) {
      echo "x is identical to y \n";
    } else {
      echo "x is not identical to y \n";
    } ?>

    Output

    This will generate the below output −

    x is equal to y 
    x is not identical to y 
    

    PHP Spaceship Operator

    Now the below code is showing the usage of spaceship operator. The spaceship operator returns three possible values – it returns -1 if the first value is smaller, returns 0 if both values are equal and returns 1 if the second value is larger.

    <?php
       $a = 5;
       $b = 10;
    
       echo ($a <=> $b), "\n"; 
    
       $a = 20;
       echo ($a <=> $b), "\n"; 
    
       $a = 10;
       echo ($a <=> $b), "\n"; 
    ?>

    Output

    This will create the below output −

    -1
    1
    0
    

    Usage of Not Equal (!=) and Not Identical (!==)

    In the following example, we are showing the usage of != and !== operators. The != operator checks if both the variables are different and !== checks that both the variables are exactly the same.

    <?php
       $p = 50;
       $q = "50";
    
       if ($p != $q) {
    
      echo "p is not equal to q \n";
    } else {
      echo "p is equal to q \n";
    } if ($p !== $q) {
      echo "p is not identical to q \n";
    } else {
      echo "p is identical to q \n";
    } ?>

    Output

    Following is the output of the above code −

    p is equal to q 
    p is not identical to q
    

    PHP Comparison and Logical Operators

    In PHP, comparison operators compare two values and logical operators combine multiple conditions. The PHP programbelow shows how to use comparison (>, <) and logical operators (&&, ||) to decide loan eligibility and special discounts.

    <?php
       $age = 25;
       $salary = 5000;
    
       if ($age > 18 && $salary > 3000) {
    
      echo "Eligible for Loan \n";
    } else {
      echo "Not Eligible for Loan \n";
    } if ($age < 30 || $salary < 1000) {
      echo "Special discount applicable \n";
    } ?>

    Output

    Following is the output of the above code −

    Eligible for Loan
    Special discount applicable

  • Arithmetic Operators Examples

    In PHP, arithmetic operators are used to perform mathematical operations on numeric values. The following table highlights the arithmetic operators that are supported by PHP. Assume variable “$a” holds 42 and variable “$b” holds 20 −

    OperatorDescriptionExample
    +Adds two operands$a + $b = 62
    Subtracts the second operand from the first$a – $b = 22
    *Multiply both the operands$a * $b = 840
    /Divide the numerator by the denominator$a / $b = 2.1
    %Modulus Operator and remainder of after an integer division$a % $b = 2
    ++Increment operator, increases integer value by one$a ++ = 43
    Decrement operator, decreases integer value by one$a — = 42

    Basic Usage of Arithmetic Operators

    The following example shows how you can use these arithmetic operators in PHP −

    <?php
       $a = 42;
       $b = 20;
    
       $c = $a + $b;
       echo "Addition Operation Result: $c \n";
    
       $c = $a - $b;
       echo "Subtraction Operation Result: $c \n";
    
       $c = $a * $b;
       echo "Multiplication Operation Result: $c \n";
    
       $c = $a / $b;
       echo "Division Operation Result: $c \n";
    
       $c = $a % $b;
       echo "Modulus Operation Result: $c \n";
    
       $c = $a++; 
       echo "Increment Operation Result: $c \n";
    
       $c = $a--; 
       echo "Decrement Operation Result: $c";
    ?>

    Output

    It will produce the following output −

    Addition Operation Result: 62 
    Subtraction Operation Result: 22 
    Multiplication Operation Result: 840 
    Division Operation Result: 2.1 
    Modulus Operation Result: 2 
    Increment Operation Result: 42 
    Decrement Operation Result: 43
    

    Arithmetic Operations with Negative Numbers

    The below PHP program performs basic mathematical operations using two numbers in which one number is negative number. So see how the arithmetic operators perform.

    <?php
       $x = -10;
       $y = 5;
    
       echo "Addition: " . ($x + $y) . "\n";  
       echo "Subtraction: " . ($x - $y) . "\n";  
       echo "Multiplication: " . ($x * $y) . "\n";  
       echo "Division: " . ($x / $y) . "\n";  
       echo "Modulus: " . ($x % $y) . "\n";  
    ?>

    Output

    It will generate the following output −

    Addition: -5  
    Subtraction: -15  
    Multiplication: -50  
    Division: -2  
    Modulus: 0  
    

    Arithmetic Operations with Floating-Point Numbers

    This PHP the program performs basic math with decimal numbers. It can do addition, subtraction, multiplicationand division operations on two numbers. The results are displayed using the echo statement.

    <?php
       $a = 5.5;
       $b = 2.2;
    
       echo "Addition: " . ($a + $b) . "\n";
       echo "Subtraction: " . ($a - $b) . "\n";
       echo "Multiplication: " . ($a * $b) . "\n";
       echo "Division: " . ($a / $b) . "\n";
    ?>

    Output

    This will generate the below output −

    Addition: 7.7  
    Subtraction: 3.3  
    Multiplication: 12.1  
    Division: 2.5  
    

    Increment and Decrement Operators

    Now the below code uses the arithmetic operators to show how the Increment and Decrement operations can be performed.

    <?php
       $count = 10;
    
       echo "Original value: " . $count . "\n";
       echo "After Increment: " . $count++ . "\n";  
       echo "After After Increment: " . $count . "\n";  
    
       echo "Before Increment: " . ++$count . "\n";  
    
       echo "Post-Decrement: " . $count-- . "\n";  
       echo "After Post-Decrement: " . $count . "\n";  
    
       echo "Pre-Decrement: " . --$count . "\n";  
    ?>

    Output

    This will create the below output −

    Original value: 10  
    After Increment: 10  
    After After Increment: 11  
    Before Increment: 12  
    Post-Decrement: 12  
    After Post-Decrement: 11  
    Pre-Decrement: 10