Author: saqibkhan

  • 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.

    Example 1

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

    Open Compiler

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

    It will produce the following output −

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

    Example 2

    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.

    Open Compiler

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

    It will produce the following output −

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

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Example 3

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

    Open Compiler

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

    It will produce the same output −

    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.

    Example 4

    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.

    Open Compiler

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

    It will produce the following output −

    x = 10  y = 20  z = 30
    

    Example 5

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

    Open Compiler

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

    It will produce the following output −

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

    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

    The syntax 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

    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.

    Open Compiler

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

    It will produce the following output −

    TEST1 : Value of result is 20
    TEST2 : Value of result is 10
    
  • Array Operators

    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.

    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.

    Example: Union Opeator in PHP

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

    Open Compiler

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

    It will produce the following output −

    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.

    Open Compiler

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

    It will produce the following output −

    bool(true)
    bool(false)
    

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    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.

    Open Compiler

    <?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);
    ?>

    It will produce the following output −

    bool(false)
    bool(true)
    
  • 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.

    The following table highligts 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 −

    Open Compiler

    <?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";
    ?>

    It will produce the following output −

    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
    
  • 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 highligts 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

    Example

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

    Open Compiler

    <?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";
    } ?>

    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
    
  • 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 highligts 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.

    Example

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

    Open Compiler

    <?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";
    } ?>

    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
    
  • 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.

    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 −

    • Arithmetic Operators
    • Comparison Operators
    • Logical Operators
    • Assignment Operators
    • String Operators
    • Array Operators
    • Conditional (or Ternary Operators)

    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 highligts 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

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    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 highligts 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 highligts 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 highligts 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 categorised 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
  • 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.

    Open Compiler

    <?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 −

    Open Compiler

    <?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
    
  • 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 onwards, 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 −

    Open Compiler

    <?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.

    Open Compiler

    <?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.

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    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 −

    Open Compiler

    <?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.

    Open Compiler

    <?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
  • 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.

    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.

    Open Compiler

    <?php
       print time();
    ?>

    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 −

    Open Compiler

    <?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; ?>

    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
    

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    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 −

    Open Compiler

    <?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());
    ?>

    It will produce the following output −

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

    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.