Blog

  • PHP – 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)
  • PHP – 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.
  • PHP – Assignment Operators Examples

    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
    
  • PHP – Logical Operators Examples

    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
  • PHP – Comparison Operators Examples

    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
  • PHP – 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 
  • PHP – Operators Types

    What are Operators in PHP?

    As in any programming language, PHP also has operators which are symbols (sometimes keywords) that are predefined to perform certain commonly required operations on one or more operands. hey are used to do calculations, compare values and make decisions in code. They are important for writing good programs.

    For example, using the expression “4 + 5” is equal to 9. Here “4” and “5” are called operands and “+” is called an operator.

    We have the following types of operators in PHP −

    This chapter will provide an overview of how you can use these operators in PHP. In the subsequent chapters, we will take a closer look at each of the operators and how they work.

    Arithmetic Operators in PHP

    We use Arithmetic operators to perform mathematical operations like addition, subtraction, multiplication, division, etc. on the given operands. Arithmetic operators (excluding the increment and decrement operators) always work on two operands, however the type of these operands should be the same.

    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 second operand from the first$a – $b = 22
    *Multiply both operands$a * $b = 840
    /Divide numerator by de-numerator$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

    Comparison Operators in PHP

    You would use Comparison operators to compare two operands and find the relationship between them. They return a Boolean value (either true or false) based on the outcome 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

    Logical Operators in PHP

    You can use Logical operators in PHP to perform logical operations on multiple expressions together. Logical operators always return Boolean values, either true or false.

    Logical operators are commonly used with conditional statements and loops to return decisions according to the Boolean conditions. You can also combine them to manipulate Boolean values while dealing with complex expressions.

    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. If both the operands are non zero then condition becomes 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

    Assignment Operators in PHP

    You can use Assignment operators in PHP to assign or update the values of a given variable with a new value. The right-hand side of the assignment operator holds the value and the left-hand side of the assignment operator is the variable to which the value will be assigned.

    The data type of both the sides should be the same, else you will get an error. The associativity of assignment operators is from right to left. PHP supports two types of assignment operators −

    • Simple Assignment Operator − It is the most commonly used operator. It is used to assign value to a variable or constant.
    • Compound Assignment Operators − A combination of the assignment operator (=) with other operators like +, *, /, etc.

    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

    String Operators in PHP

    There are two operators in PHP for working with string data types −

    • 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.
    • 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.
    $third=$first.$second;$leftstring.=$rightstring;

    Array Operators in PHP

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

    SymbolExampleNameResult
    +$a + $bUnionUnion of $a and $b.
    ==$a == $bEqualityTRUE if $a and $b have the same key/value pairs.
    ===$a === $bIdentityTRUE if $a and $b have the same key/value pairs in the same order and of the same types.
    !=$a != $bInequalityTRUE if $a is not equal to $b.
    <>$a <> $bInequalityTRUE if $a is not equal to $b.
    !==$a !== $bNon identityTRUE if $a is not identical to $b.

    Conditional Operators in PHP

    There is one more operator in PHP which is called conditional operator. 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.

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

    Operator Categories in PHP

    All the operators we have discussed above can be categorized into following categories −

    • Unary prefix operators, which precede a single operand.
    • Binary operators, which take two operands and perform a variety of arithmetic and logical operations.
    • The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression.
    • Assignment operators, which assign a value to a variable.

    Operator Precedence in PHP

    Precedence of operators decides the order of execution of operators in an expression. For example, in “2+6/3”, division of 6/3 is done first and then the addition of “2+2” takes place because the division operator “/” has higher precedence over the addition operator “+”.

    To force a certain operator to be called before other, parentheses should be used. In this example, (2+6)/3 performs addition first, followed by division.

    Some operators may have the same level of precedence. In that case, the order of associativity (either left or right) decides the order of operations. Operators of same precedence level but are non-associative cannot be used next to each other.

    The following table lists the PHP operators in their decreasing order of precedence −

    OperatorsPurpose
    clone newclone and new
    **exponentiation
    ++ —increment/decrement
    ~(int) (float) (string) (array) (object) (bool)casting
    instanceoftypes
    !logical
    * /multiplication/division
    %modulo
    + – .arithmetic and string
    << >>bitwise shift
    < <= > >=comparison
    == != === !== <> <=>comparison
    &bitwise and/references
    ^bitwise XOR
    |bitwise OR
    &&logical and
    ||logical or
    ??null coalescing
    ? :ternary
    = += -= *= **= /= .= %= &= |= ^= <<= >>= ??=assignment operators
    yield fromyield from
    yieldyield
    printprint
    andlogical
    xorlogical
    orlogical
  • PHP – Return Type Declarations

    PHP version 7 extends the scalar type declaration feature to the return value of a function also. As per this new provision, the return type declaration specifies the type of value that a function should return. We can declare the following types for return types −

    • int
    • float
    • bool
    • string
    • interfaces
    • array
    • callable

    To implement the return type declaration, a function is defined as −

    functionmyfunction(type$par1,type$param2):type{# function bodyreturn$val;}

    PHP parser is coercive typing by default. You need to declare “strict_types=1” to enforce stricter verification of the type of variable to be returned with the type used in the definition.

    Example

    In the following example, the division() function is defined with a return type as int.

    <?php
       function division(int $x, int $y): int {
          $z = $x/$y;
          return $z;
       }
    
       $x=20.5;
       $y=10;
    
       echo "First number: " . $x; 
       echo "\nSecond number: " . $y; 
       echo "\nDivision: " . division($x, $y);
    ?>

    Since the type checking has not been set to strict_types=1, the division take place even if one of the parameters is a non-integer.

    First number: 20.5
    Second number: 10
    Division: 2
    

    However, as soon as you add the declaration of strict_types at the top of the script, the program raises a fatal error message.

    Fatal error: Uncaught TypeError:division():Argument#1 ($x) must be of type int, float given, called in div.php on line 12 and defined in div.php:3
    Stack trace:#0 div.php(12): division(20.5, 10)#1 {main}
       thrown in div.php on line 3

    VS Code warns about the error even before running the code by displaying error lines at the position of error −

    PHP Return Type Declarations

    Example

    To make the division() function return a float instead of int, cast the numerator to float, and see how PHP raises the fatal error −

    <?php
       // declare(strict_types=1);
       function division(int $x, int $y): int {
          $z = (float)$x/$y;
          return $z;
       }
    
       $x=20;
       $y=10;
    
       echo "First number: " . $x; 
       echo "\nSecond number: " . $y; 
       echo "\nDivision: " . division($x, $y);
    ?>

    Uncomment the declare statement at the top and run this code here to check its output. It will show an error −

    First number: 20
    Second number: 10PHP Fatal error:  Uncaught TypeError: division(): Return value must be of type int, float returned in /home/cg/root/14246/main.php:5
    Stack trace:
    #0 /home/cg/root/14246/main.php(13): division()
    #1 {main}
      thrown in /home/cg/root/14246/main.php on line 5
  • PHP – Scalar Type Declarations

    The feature of providing type hints has been in PHP since version 5. Type hinting refers to the practice of providing the data type of a parameter in the function definition. Before PHP 7, it was possible to use only the array, callable, and class for type hints in a function. PHP 7 onward, you can also insert type hints for parameters of scalar data type such as int, string, bool, etc.

    PHP is a dynamically (and weakly) typed language. Hence, you don’t need to declare the type of the parameter when a function is defined, something which is necessary in a statically type language like C or Java.

    A typical definition of function in PHP is as follows −

    functionaddition($x,$y){echo"First number: $x Second number: $y Addition: ".$x+$y;}

    Here, we assume that the parameters $x and $y are numeric. However, even if the values passed to the function aren’t numeric, the PHP parser tries to cast the variables into compatible type as far as possible.

    If one of the values passed is a string representation of a number, and the second is a numeric variable, PHP casts the string variable to numeric in order to perform the addition operation.

    Example

    Take a look at this following example −

    <?php
       function addition($x, $y) {
          echo "First number: " . $x; 
          echo "\nSecond number: " . $y; 
          echo "\nAddition: " . $x+$y;
       }
    
       $x="10";
       $y=20;
       addition($x, $y);
    ?>

    It will produce the following output −

    First number: 10
    Second number: 20
    Addition: 30
    

    However, if $x in the above example is a string that doesn’t hold a valid numeric representation, an error is encountered.

    <?php
       function addition($x, $y) {
          echo "First number: " . $x; 
          echo "\nSecond number: " . $y; 
          echo "\nAddition: " . $x+$y;
       }
    
       $x="Hello";
       $y=20;
       addition($x, $y);
    ?>

    Run this code and see how it shows an error.

    Scalar Type Declarations in PHP 7

    A new feature introduced with PHP version 7 allows defining a function with parameters whose data type can be specified within the parenthesis.

    PHP 7 has introduced the following Scalar type declarations −

    • Int
    • Float
    • Bool
    • String
    • Interfaces
    • Array
    • Callable

    Older versions of PHP allowed only the array, callable and class types to be used as type hints. Furthermore, in the older versions of PHP (PHP 5), the fatal error used to be a recoverable error while the new release (PHP 7) returns a throwable error.

    Scalar type declaration is implemented in two modes −

    • Coercive Mode − Coercive is the default mode and need not to be specified.
    • Strict Mode − Strict mode has to be explicitly hinted.

    Coercive Mode

    The addition() function defined in the earlier example can now be re-written by incorporating the type declarations as follows −

    functionaddition(int$x,int$y){echo"First number: $x Second number: $y Addition: ".$x+$y;}

    Note that the parser still casts the incompatible types i.e., string to an int if the string contains an integer as earlier.

    Example

    Take a look at this following example −

    <?php
       function addition(int $x, int $y) {
          echo "First number: " . $x;
          echo "\nSecond number: " . $y;
          echo "\nAddition: " . $x+$y;
       }
    
       $x="10";
       $y=20;
       echo addition($x, $y);
    ?>

    It will produce the following output −

    First number: 10
    Second number: 20
    Addition: 30
    

    Obviously, this is because PHP is a weakly typed language, as PHP tries to coerce a variable of string type to an integer. PHP 7 has introduced a strict mode feature that addresses this issue.

    Strict Mode

    To counter the weak type checking of PHP, a strict mode has been introduced. This mode is enabled with a declare statement −

    declare(strict_types=1);

    You should put this statement at the top of the PHP script (usually just below the PHP tag). This means that the strictness of typing for scalars is configured on a per-file basis.

    In the weak mode, the strict_types flag is 0. Setting it to 1 forces the PHP parser to check the compatibility of the parameters and values passed. Add this statement in the above code and check the result. It will show the following error message −

    Fatal error: Uncaught TypeError:addition():Argument#1 ($x) must be of type int, string given, 
    called in add.php on line 12and defined in add.php:4
    
    Stack trace:#0 add.php(12): addition('10', 20)#1 {main}
       thrown in add.php on line 4

    Example

    Here is another example of scalar type declaration in the function definition. The strict mode when enabled raises fatal error if the incompatible types are passed as parameters.

    <?php
       // Strict mode
       // declare(strict_types = 1);
       function sum(int ...$ints) {
          return array_sum($ints);
       }
       print(sum(2, '3', 4.1));
    ?>

    Uncomment the declare statement at the top of this code and run it. Now it will produce an error −

    Fatal error: Uncaught TypeError: 
    sum(): Argument #2 must be of type int, string given, 
    called in add.php on line 9 and defined in add.php:4
    Stack trace:
    #0 add.php(9): sum(2, '3', 4.1)
    #1 {main}
       thrown in add.php on line 4
    

    The type-hinting feature is mostly used by IDEs to prompt the user about the expected types of the parameters used in the function declaration. The following screenshot shows the VS Code editor popping up the function prototype as you type.

    PHP Scalar Type Declarations
  • PHP – Date & Time

    The built-in library of PHP has a wide range of functions that helps in programmatically handling and manipulating date and time information. Date and Time objects in PHP can be created by passing in a string presentation of date/time information, or from the current system’s time.

    PHP provides the DateTime class that defines a number of methods. In this chapter, we will have a detailed view of the various Date and Time related methods available in PHP.

    The date/time features in PHP implements the ISO 8601 calendar, which implements the current leap-day rules from before the Gregorian calendar was in place. The date and time information is internally stored as a 64-bit number.

    Here are the topics we will cover in this chapter −

    Getting the Time Stamp with time()

    PHP’s time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer.

    time():int

    The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp.

    <?php
       print time();
    ?>

    Output

    It will produce the following output −

    1699421347
    

    We can convert a time stamp into a form that humans are comfortable with.

    Converting a Time Stamp with getdate()

    The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time().

    The following table lists the elements contained in the array returned by getdate().

    Sr.NoKey & DescriptionExample
    1secondsSeconds past the minutes (0-59)20
    2minutesMinutes past the hour (0 – 59)29
    3hoursHours of the day (0 – 23)22
    4mdayDay of the month (1 – 31)11
    5wdayDay of the week (0 – 6)4
    6monMonth of the year (1 – 12)7
    7yearYear (4 digits)1997
    8ydayDay of year ( 0 – 365 )19
    9weekdayDay of the weekThursday
    10monthMonth of the yearJanuary
    110Timestamp948370048

    Now you have complete control over date and time. You can format this date and time in whatever format you want.

    Example

    Take a look at this following example −

    <?php
       $date_array = getdate();
    
       foreach ( $date_array as $key => $val ){
          print "$key = $val\n";
       }
       $formated_date  = "Today's date: ";
       $formated_date .= $date_array['mday'] . "-";
       $formated_date .= $date_array['mon'] . "-";
       $formated_date .= $date_array['year'];
    
       print $formated_date;
    ?>

    Output

    It will produce the following output −

    seconds = 0
    minutes = 38
    hours = 6
    mday = 8
    wday = 3
    mon = 11
    year = 2023
    yday = 311
    weekday = Wednesday
    month = November
    0 = 1699421880
    Today's date: 8-11-2023
    

    Converting a Time Stamp with date()

    The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it.

    date(string$format,?int$timestamp=null):string

    The date() optionally accepts a time stamp if omitted then current date and time will be used. Any other data you include in the format string passed to date() will be included in the return value.

    The following table lists the codes that a format string can contain −

    Sr.NoFormat & DescriptionExample
    1a‘am’ or ‘pm’ lowercasepm
    2A‘AM’ or ‘PM’ uppercasePM
    3dDay of month, a number with leading zeroes20
    4DDay of week (three letters)Thu
    5FMonth nameJanuary
    6hHour (12-hour format – leading zeroes)12
    7HHour (24-hour format – leading zeroes)22
    8gHour (12-hour format – no leading zeroes)12
    9GHour (24-hour format – no leading zeroes)22
    10iMinutes ( 0 – 59 )23
    11jDay of the month (no leading zeroes20
    12l (Lower ‘L’)Day of the weekThursday
    13LLeap year (‘1’ for yes, ‘0’ for no)1
    14mMonth of year (number – leading zeroes)1
    15MMonth of year (three letters)Jan
    16rThe RFC 2822 formatted dateThu, 21 Dec 2000 16:01:07 +0200
    17nMonth of year (number – no leading zeroes)2
    18sSeconds of hour20
    19UTime stamp948372444
    20yYear (two digits)06
    21YYear (four digits)2006
    22zDay of year (0 – 365)206
    23ZOffset in seconds from GMT+5

    Example

    Take a look at this following example −

    <?php
       print date("m/d/y G.i:s \n", time()) . PHP_EOL;
       print "Today is ";
       print date("j of F Y, \a\\t g.i a", time());
    ?>

    Output

    It will produce the following output −

    11/08/23 11.23:08
    
    Today is 8 2023f November 2023, at 11.23 am
    

    Formatting Date and Time

    You can format the date and time in different ways with the help of the date() function. Here are some examples −

    Have a look at this following example −

    <?php
       echo date("d/m/Y"); 
       echo "\n";
       echo date("l, F j, Y"); 
    ?>

    Output

    It will create the below output −

    17/02/2025
    Monday, February 17, 2025
    

    Converting Strings to Dates

    The strtotime() function converts a string-formatted date to a timestamp. This is useful when manipulating and computing dates.

    Have a look at the below example showing the usage of strtotime() function −

    <?php
       $date = "2025-02-17";
       $timestamp = strtotime($date);
       echo $timestamp; 
    ?>

    Output

    It will produce the below output −

    1739750400
    

    Hope you have good understanding on how to format date and time according to your requirement. For your reference a complete list of all the date and time functions is given in PHP Date & Time Functions.