Category: PHP

  • Strict Typing

    PHP is widely regarded as a weakly typed language. In PHP, you need not declare the type of a variable before assigning it any value. The PHP parser tries to cast the variables into compatible type as far as possible.

    For example, 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.

    Automatic Type Casting in Addition

    PHP converts the string to a number to perform the addition operation. Take a look at the following example −

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

    It will produce the following output −

    First number: 10 Second number: 20 Addition: 30
    

    Error by Adding Non-Numeric String to a Number

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

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

    It will produce the following output −

    PHP Fatal error:  Uncaught TypeError: Unsupported operand 
    types: string + int in hello.php:5
    

    Type Hints

    Type-hinting is supported from PHP 5.6 version onwards. It means you can explicitly state the expected type of a variable declared in your code. PHP allows you to type-hint function arguments, return values, and class properties. With this, it is possible to write more robust code.

    Let us incorporate type-hinting in the addition function in the above program −

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

    Note that by merely using the data types in the variable declarations doesn’t prevent the unmatched type exception raised, as PHP is a dynamically typed language. In other words, $x=”10″ and $y=20 will still result in the addition as 30, whereas $x=”Hello” makes the parser raise the error.

    Example

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

    It will produce the following output −

    First number: 10 
    Second number: 20 
    Addition: 30
    
    First number: 10 
    Second number: 20 
    Addition: 30
    
    First number: Hello 
    Second number: 20
    PHP Fatal error:  Uncaught TypeError: Unsupported operand 
    types: string + int in hello.php:5
    

    Using strict_types

    PHP can be made to impose stricter rules for type conversion, so that “10” is not implicitly converted to 10. This can be enforced by setting strict_types directive to 1 in a declare() statement.

    The declare() statement must be the first statement in the PHP code, just after the “<?php” tag.

    Example

    Take a look at the following example −

    <?php
       declare (strict_types=1);
       function addition(int $x, int $y) {
    
      echo "First number: $x Second number: $y Addition: " . $x+$y;
    } $x=10; $y=20; addition($x, $y); ?>

    It will produce the following output −

    First number: 10 Second number: 20 Addition: 30
    

    Now, if $x is set to “10”, the implicit conversion won’t take place, resulting in the following error −

    PHP Fatal error:  Uncaught TypeError: addition(): Argument #1 
    ($x) must be of type int, string given
    

    From PHP 7 onwards, type-hinting support has been extended for function returns to prevent unexpected return values. You can type-hint the return values by adding the intended type after the parameter list prefixed with a colon (:) symbol.

    Example

    Let us add a type hint to the return value of the division() function below.

    <?php
       declare (strict_types=1);
       function division(int $x, int $y) : int {
    
      return $x/$y;
    } $x=10; $y=20; $result = division($x, $y); echo "First number: $x Second number: $y Addition: " . $result; ?>

    Because the function returns 0.5, which is not of int type (that is, the type hint used for the return value of the function), the following error is displayed −

    Fatal error: Uncaught TypeError: division(): Return value must be 
    of type int, float returned in hello.php:5
    

    Benefits of PHP Strict Typing

    Here are the benefits of using the strict typing in your code −

    • Strict typing improves code reliability to ensure type safety, reducing the risk of runtime errors due by incorrect data types.
    • Explicit type definitions improve code readability by making it self-explanatory and understandable.
    • When developers understand the different sorts of variables, it is easier to change and update the code without creating new errors.
  • Variable Scope

    In PHP, the scope of a variable is the context within which it is defined and accessible to the extent in which it is accessible. Generally, a simple sequential PHP script that doesnt have any loop or a function etc., has a single scope. Any variable declared inside the “<?php” and “?>” tag is available throughout the program from the point of definition onwards.

    Variable Scope Types

    Based on the scope, a PHP variable can be any of these types −

    • Local Variables
    • Global Variables
    • $GLOBALS Array
    • Static Variables

    A variable in a main script is also made available to any other script incorporated with include or require statements.

    Using Local Variables

    In the following example, a “test.php” script is included in the main script.

    main.php

    <?php
       $var=100;
       include "test.php";
    ?>

    test.php

    <?php
       echo "value of \$var in test.php : " . $var;
    ?>

    When the main script is executed, it will display the following output −

    value of $var in test.php : 100
    

    However, when the script has a user defined function, any variable inside has a local scope. As a result, a variable defined inside a function can’t be accessed outside. Variables defined outside (above) the function have a global scope.

    Using Global Variables

    Take a look at the following example −

    <?php
       // global variable   
       $var=100;   
       function myfunction() {
    
      // local variable
      $var1="Hello"; 	
      echo "var=$var  var1=$var1" . PHP_EOL;
    } myfunction(); echo "var=$var var1=$var1" . PHP_EOL; ?>

    Output

    It will produce the following output −

    var=  var1=Hello
    var=100  var1=
    
    PHP Warning:  Undefined variable $var in /home/cg/root/64504/main.php on line 5
    PHP Warning:  Undefined variable $var1 in /home/cg/root/64504/main.php on line 8
    

    Note that a global variable is not automatically available within the local scope of a function. Also, the variable inside a function is not accessible outside.

    The ‘global’ Keyword

    To enable access to a global variable inside local scope of a function, it should be explicitly done by using the “global” keyword.

    Example

    The PHP script is as follows −

    <?php
       $a=10; 
       $b=20;
       echo "Global variables before function call: a = $a b = $b" . PHP_EOL;
       function myfunction() {
    
      global $a, $b;
      $c=($a+$b)/2;
      echo "inside function a = $a b = $b c = $c" . PHP_EOL;
      $a=$a+10;
    } myfunction(); echo "Variables after function call: a = $a b = $b c = $c"; ?>

    Output

    It will produce the following output −

    Global variables before function call: a = 10 b = 20
    inside function a = 10 b = 20 c = 15
    Variables after function call: a = 20 b = 20 c = 
    PHP Warning:  Undefined variable $c in /home/cg/root/48499/main.php on line 12
    

    Global variables can now be processed inside the function. Moreover, any changes made to the global variables inside the function will be reflected in the global namespace.

    Accessing Global Variables with $GLOBALS Array

    PHP stores all the global variables in an associative array called $GLOBALS. The name and value of the variables form the key-value pair.

    Example

    In the following PHP script, $GLOBALS array is used to access global variables −

    <?php
       $a=10; 
       $b=20;
       echo "Global variables before function call: a = $a b = $b" . PHP_EOL;
    
       function myfunction() {
    
      $c=($GLOBALS['a']+$GLOBALS['b'])/2;
      echo "c = $c" . PHP_EOL;
      $GLOBALS['a']+=10;
    } myfunction(); echo "Variables after function call: a = $a b = $b c = $c"; ?>

    Output

    It will produce the following output −

    Global variables before function call: a = 10 b = 20
    c = 15
    PHP Warning:  Undefined variable $c in C:\xampp\htdocs\hello.php on line 12
    Variables after function call: a = 20 b = 20 c =
    

    Static Variable

    A variable defined with static keyword is not initialized at every call to the function. Moreover, it retains its value of the previous call.

    Example

    Take a look at the following example −

    <?php
       function myfunction() {
    
      static $x=0;
      echo "x = $x" . PHP_EOL;
      $x++;
    } for ($i=1; $i<=3; $i++) {
      echo "call to function :$i : ";
      myfunction();
    } ?>

    Output

    It will produce the following output −

    call to function :1 : x = 0
    call to function :2 : x = 1
    call to function :3 : x = 2

  • Type Hints

    PHP supports using “type hints” at the time of declaring variables in the function definition and properties or instance variables in a class. PHP is widely regarded as a weakly typed language. In PHP, you need not declare the type of a variable before assigning it any value.

    The PHP parser tries to cast the variables into compatible type as far as possible. Hence, if one of 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.

    Type Casting in Function Parameters

    In PHP, type casting in function parameters allows you to define the type of value that a function will accept. This helps to find errors and makes your code more reliable.

    Take a look at the following example −

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

    Output

    It will generate the following output −

    First number: 10 Second number: 20 Addition: 30
    

    When Type Conversion Fails in PHP?

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

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

    Output

    It will produce the following output −

    PHP Fatal error:  Uncaught TypeError: Unsupported operand types: string + int in hello.php:5
    

    Using Type Hints in PHP Functions

    Type-hinting is supported from PHP 5.6 version onwards. It means you can explicitly state the expected type of a variable declared in your code. PHP allows you to type-hint function arguments, return values, and class properties. With this, it is possible to write more robust code.

    Let us incorporate type-hinting in the addition function in the above program −

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

    The type-hinting feature is mostly used by IDEs (Integrated Development Environment) to prompt the user about the expected types of the parameters used in function declaration.

    The following figure shows the VS Code editor popping up the function prototype as you type −

    PHP Type Hints 1

    If the cursor hovers on the name of the function, the type declarations for the parameters and the return value are displayed −

    PHP Type Hints 2

    Note that by merely using the data types in the variable declarations doesnt prevent the unmatched type exception raised, as PHP is a dynamically typed language. In other words, $x=”10″ and $y=20 will still result in the addition as 30, where as $x=”Hello” makes the parser raise the error.

    Strict Type Checking in PHP

    PHP can be made to impose stricter rules for type conversion, so that “10” is not implicitly converted to 10. This can be enforced by setting strict_types directive to 1 in a declare() statement. The declare() statement must be the first statement in the PHP code, just after the “<?php” tag.

    Example

    <?php
       declare (strict_types=1);
       function addition(int $x, int $y) {
    
      echo "First number: $x Second number: $y Addition: " . $x+$y;
    } $x=10; $y=20; addition($x, $y); ?>

    Output

    It will produce the following output −

    First number: 10 Second number: 20 Addition: 30
    

    Now, if $x is set to “10”, the implicit conversion wont take place, resulting in the following error −

    PHP Fatal error:  Uncaught TypeError: addition(): Argument #1 ($x) must be of type int, string given
    

    The VS Code IDE too indicates the error of the same effect −

    PHP Type Hints 3

    PHP Return Type Declarations

    From PHP 7 onwards with type-hinting support has been extended for function returns to prevent unexpected return values. You can type-hint return values by adding the intended type after the parameter list prefixed with a colon (:) symbol.

    Example

    Let us add a type hint to the return value of the addition function above −

    <?php
       declare (strict_types=1);
       function addition(int $x, int $y) : int {
    
      return $x+$y;
    } $x=10; $y=20; $result = addition($x, $y); echo "First number: $x Second number: $y Addition: " . $result; ?>

    Output

    The above code will produce the following output −

    First number: 10 Second number: 20 Addition: 30
    

    Here too, if the function is found to return anything other than an integer, the IDE indicates the reason even before you run.

    PHP Type Hints 4

    PHP Union Types

    The PHP introduced union types with its version 8.0. You can now specify more than one type for a single declaration. The data types are separated by the “|” symbol.

    Example

    In the definition of addition() function below, the $x and $y arguments can be of int or float type.

    <?php
       declare (strict_types=1);
       function addition(int|float $x, int|float $y) : float {
    
      return $x+$y;
    } $x=10.55; $y=20; $result = addition($x, $y); echo "First number: $x Second number: $y Addition: " . $result; ?>

    Output

    The output of the above code will be as following −

    First number: 10.55 Second number: 20 Addition: 30.55
    

    Type-hinting in Class

    In PHP, from version 7.4 onwards, you can use the type hints in declaration of class properties and methods. This helps catch type related issues early which makes the code more reliable and easier to debug.

    Example

    In the following example, the class constructor uses type hints −

    <?php
       declare (strict_types=1);
       class Student {
    
      public $name;
      public $age;
      public function __construct(string $name, int $age) {
         $this-&gt;name = $name;
         $this-&gt;age = $age;
      }
      public function dispStudent() {
         echo "Name: $this-&gt;name Age: $this-&gt;age";
      }
    } $s1 = new Student("Amar", 21); $s1->dispStudent(); ?>

    Output

    Here is the output of the above code −

    Name: Amar Age: 21
    

    It is also possible to use type hints in the declaration of class properties.

    classStudent{publicstring$name;publicint$age;publicfunction__construct($name,$age){$this->name=$name;$this->age=$age;}publicfunctiondispStudent(){echo"Name: $this->name Age: $this->age";}}

    Nullable Type

    A nullable type means that a parameter or return result can be either a certain type or null. To allow null values, add a ? before the type.

    Example

    In the following example, we are using the Nullable type hint. See the example below −

    <?php
       function greet(?string $name) {
    
      if ($name === null) {
         echo "Hello, Guest!";
      } else {
         echo "Hello, $name!";
      }
    } greet("Jatin"); echo "\n"; greet(null); ?>

    Output

    Following is the output of the above code −

    Hello, Jatin!
    Hello, Guest!
    

    Mixed Type

    A mixed type parameter accepts any type of value, such as texts, integers, arrays, and objects.

    <?php
       function display(mixed $value) {
    
      var_dump($value);
    } display("Hello"); display(123); display([1, 2, 3]); ?>

    Output

    Following is the output of the above code −

    string(5) "Hello"
    int(123)
    array(3) {
      [0]=>
      int(1)
      [1]=>
      int(2)
      [2]=>
      int(3)
    }
    

    The most commonly encountered errors during program development are type errors. The type-hinting feature helps in reducing them.

  • Recursive Functions

    A recursive function is such a function that calls itself until a certain condition is satisfied. In PHP, it is possible to defines a recursive function.

    • Recursion is used when a certain problem is defined in terms of itself.
    • Sometimes, it can be tedious to solve a problem using iterative approach. Recursive approach provides a very concise solution to seemingly complex problems.
    • Recursion in PHP is very similar to the one in C and C++.
    • Recursive functions are particularly used in traversing nested data structures, and searching or sorting algorithms.
    • Binary tree traversal, heap sort and finding shortest route are some of the cases where recursion is used.

    Calculation of Factorial using Recursion

    The most popular example of recursion is calculation of factorial. Mathematically factorial is defined as −

    n!=n(n-1)!

    It can be seen that we use factorial itself to define factorial. Hence, this is a fit case to write a recursive function.

    Let us expand the above definition for calculation of factorial value of 5

    5!=54!543!5432!54321!54321=120

    While we can perform this calculation using a loop, its recursive function involves successively calling it by decrementing the number till it reaches 1.

    Example

    Following is the recursive function to calculate factorial.

    <?php
       function factorial ($n) {
    
      if ($n == 1) {
         echo $n . PHP_EOL;
         return 1;
      } else {
         echo "$n * ";
         return $n*factorial($n-1);
      }
    } echo "Factorial of 5 = " . factorial(5); ?>

    Output

    It will produce the following output −

    5 * 4 * 3 * 2 * 1
    Factorial of 5 = 120
    

    Binary Search using Recursion

    Let us have a look at another example to understand how recursion works. The problem at hand is to check whether a given number is present in a list.

    While we can perform a sequential search for a certain number in the list using a for loop and comparing each number, the sequential search is not efficient especially if the list is too large. Here, we can use the binary search algorithm that checks if the index ‘high’ is greater than index ‘low. Based on the value present at ‘mid’ variable, the function is called again to search for the element.

    We have a list of numbers, arranged in ascending order. Then, we find the midpoint of the list and restrict the checking to either left or right of midpoint depending on whether the desired number is less than or greater than the number at midpoint.

    The following diagram shows how binary search works −

    PHP Recursive Functions

    Example

    The following code implements the recursive binary searching technique −

    <?php
       function bsearch($my_list, $low, $high, $elem) {
    
      if ($high &gt;= $low) {
         $mid = intval(($high + $low)/2);
         if ($my_list[$mid] == $elem)
         return $mid;
         elseif ($my_list[$mid] &gt; $elem)
         return bsearch($my_list, $low, $mid - 1, $elem);
         else
         return bsearch($my_list, $mid + 1, $high, $elem);
      }
      else
      return -1;
    } $list = [5,12,23, 45, 49, 67, 71, 77, 82]; $num = 67; $result = bsearch($list,0,count($list)-1, $num); if ($result != -1) echo " Number $num found at index " . $result; else echo "Element not found!"; ?>

    Output

    It will produce the following output −

    Number 67 found at index 5
    

    You can check the output for different numbers present in the given list, as well as those which are not present in the list.

  • Passing Functions

    To a function in PHP, in addition to scalar types, arrays, and objects, you can also pass a function as one of its arguments. If a function is defined to accept another function as an argument, the passed function will be invoked inside it. PHPs standard library has certain built-in functions of this type, where one of the arguments to be passed is a function, which may be another built-in function or even a user defined function.

    Using array_map() to Pass a Function

    The array_map() is one of the built-in functions. The first argument to this function is a callback function. There may be one or more arrays as the other arguments. The callback function is applied to all the elements of arrays.

    array_map(?callable$callback,array$array,array...$arrays):array

    The array_map() function returns an array. It contains the result of applying the callback function to the corresponding elements of arrays passed as other arguments.

    Example

    In the following example, we have a square() function that computes the square of a number passed to it. This function in turn is used as an argument for array_map() function, along with another array of numbers. Each number is successively passed to the squares() function. The resultant array is a list of squares.

    <?php
       function square($number) {
    
      return $number * $number;
    } $arr = [1, 2, 3, 4, 5]; $squares = array_map('square', $arr); var_dump($squares); ?>

    Output

    It will produce the following output −

    array(5) {
       [0]=>
       int(1)
       [1]=>
       int(4)
       [2]=>
       int(9)
       [3]=>
       int(16)
       [4]=>
       int(25)
    }
    

    Usage of call_user_func() Function

    Another example of passing a function to another function is call_user_func(). As the name suggests, it calls another user defined callback function, and the other arguments are passed to the callback.

    call_user_func(callable$callback,mixed...$args):mixed

    Example

    In the example below, the square() function is invoked repeatedly, passing each number in an array.

    <?php
       function square($number) {
    
      return $number * $number;
    } $arr = [1, 2, 3, 4, 5]; foreach($arr as $a) {
      echo "square of $a:" . call_user_func("square", $a). PHP_EOL;
    } ?>

    Output

    It will produce the following output −

    square of 1:1
    square of 2:4
    square of 3:9
    square of 4:16
    square of 5:25
    

    Usage of usort() Function

    As another example of passing function, we take a look a usort() function.

    usort(array&$array,callable$callback):true

    The first parameter is an array. The array is sorted as per the callback function, which is the second parameter.

    The callback parameter is a comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

    Example

    Here is an example. First we have a mysort() function. It compares two numbers and returns “-1”, “0” or “1” if the first number is less than, equal to or greater than second number.

    The first argument to usort() is the mysort() function, and the second one is an array. To begin with, the first two numbers are passed to mysort(). If it returns 1, they are swapped. Next, the second and third numbers are passed and swapped if the comparison returns 1. The same process repeats so that the array elements are arranged in ascending order.

    <?php
       function mysort($a, $b) {
    
      if ($a == $b) {
         return 0;
      }
      return ($a &lt; $b) ? -1 : 1;
    } $a = array(3, 2, 5, 6, 1); usort($a, "mysort"); foreach ($a as $key => $value) {
      echo "$key: $value\n";
    } ?>

    Output

    It will produce the following output −

    0: 1
    1: 2
    2: 3
    3: 5
    4: 6
    

    Pass Callback to User-defined Function

    Apart from the above built-in functions, you can define your own function that accepts one of the arguments as another function.

    In the example below, we have two functions, square() and cube(), that return the square and cube of a given number.

    Next, there is myfunction(), whose first argument is used as a variable function and the second argument to myfunction() is passed to it.

    Thus, myfunction() internally calls square() or cube() to return either square or cube of a given number.

    Example

    <?php
       function myfunction($function, $number) {
    
      $result = $function($number);
      return $result;
    } function cube($number) {
      return $number ** 2;
    } function square($number) {
      return $number ** 3;
    } $x = 5; $cube = myfunction('cube', $x); $square = myfunction('square', $x); echo "Square of $x = $square" . PHP_EOL; echo "Cube of $x = $cube" . PHP_EOL; ?>

    Output

    It will produce the following output −

    Square of 5 = 125
    Cube of 5 = 25
    
  • Returning Values

    A PHP function can have an optional return statement as the last statement in its function body. Most of the built-in functions in PHP return a certain value. For example the strlen() function returns the length of a string. Similarly, a user defined function can also return a certain value.

    A function is an independent, complete and reusable block of statements. When called, it performs a certain task and sends the program control back to position from where it was called even if return statement is not used. The return statement allows it to take a value, along with the control, back to the calling environment.

    functionfoo($arg_1,$arg_2){
       statements;return$retval;}

    A function may return any type of data, including scalar variables, arrays and objects. A return keyword without any expression in front of it returns null, and is equivalent to a function not having a return value at all.

    The value returned by a function can be stored in a variable, can be put in an expression, or, if appearing inside print or echo, is displayed in the output.

    $res=foo($x,$y);

    It allows the returned value of a function to be used further in the program.

    Example

    Let us modify the addition() function in the previous chapter to include a return statement to return the result of addition.

    <?php
       function addition($first, $second) {
    
      $result = $first+$second;
      return $result;
    } $x=10; $y=20; $z = addition($x, $y); echo "First number: $x Second number: $y Addition: $z". PHP_EOL; ?>

    Output

    It will produce the following output −

    First number: 10 Second number: 20 Addition: 30
    

    A function in PHP may have any number of arguments, but can return only one value. The function goes back to the calling environment as soon as it comes across a return statement for the first time, abandoning the rest of statements in the function body.

    Example

    If you try to include more than one values in the return statement, a PHP parse error is encountered as below −

    <?php
       function raiseto($x) {
    
      $sqr =  $x**2;
      $cub =  $x**3;
      return $sqr, $cub;
    } $a = 5; $val = raiseto($a); ?>

    Output

    It will produce the following output −

    PHP Parse error: syntax error, unexpected token ",", expecting ";" 
    

    Conditional Return

    You can have multiple return statements executed under different conditional statements.

    Example

    In the following program, the raiseto() function returns either the square or the cube of a number of the index argument, that is either 2 or 3, respectively.

    <?php
       function raiseto($x, $i) {
    
      if ($i == 2) {
         return $x**2;
      } elseif ($i==3) {
         return $x**3;
      }
    } $a = 5; $b = 2; $val = raiseto($a, $b); echo "$a raised to $b = $val" . PHP_EOL; $x = 7; $y = 3; echo "$x raised to $y = " . raiseto($x, $y) . PHP_EOL; ?>

    Output

    It will produce the following output −

    5 raised to 2 = 25
    7 raised to 3 = 343
    

    Return Multiple Values as Array

    The function in PHP is capable of returning only a single value. However, that single value can be an array of more than one values. We can take the advantage of this feature to return the square as well as the cube of a number at once.

    Example

    Take a look at the following example −

    <?php
       function raiseto($x){
    
      $sqr =  $x**2;
      $cub =  $x**3;
      $ret = ["sqr" =&gt; $sqr, "cub" =&gt; $cub];
      return $ret;
    } $a = 5; $val = raiseto($a); echo "Square of $a: " . $val["sqr"] . PHP_EOL; echo "Cube of $a: " . $val["cub"] . PHP_EOL; ?>

    Output

    It will produce the following output −

    Square of 5: 25
    Cube of 5: 125
  • Variable Arguments

    In PHP, it is possible to write a function capable of accepting a list of arguments with variable number of elements. To declare a variable argument list, the name of the argument is prepended by the “…” (three dots) symbol. The values passed are collected into an array with the argument’s name.

    Here is the syntax we can use for defining the variable arguments −

    functionmyfunction(...$arg){
       Statement1;
       Statement2;}

    Call the Function with Variable Arguments

    To call such a function, put any number of comma-separated values in the parenthesis.

    myfunction(v1, v2, v3,..., vn);

    The formal argument declared in the function is an array of all the values passed. We van use any of the appropriate built_in array functions to perform the process.

    Example

    In the following example, the user defined function myfunction() is capable of receiving variable number of values and finds their average.

    <?php  
       function  myfunction(...$numbers) {
    
      $avg = array_sum($numbers)/count($numbers);
      return $avg;
    } $avg = myfunction(5, 12, 9, 23, 8); echo "average = $avg"; ?>

    Output

    It will produce the following output −

    average = 11.4
    

    Try changing the size of the passed array and run the program again.

    You can use a foreach loop to traverse the array inside the function. The function may have any positional arguments before the variable length argument. From the received values, the positional arguments will be populated first, leaving others to be copied to the array.

    Example

    <?php
       function myfunction($x, ...$numbers) {
    
      echo "First number: $x" . PHP_EOL;
      echo "Remaining numbers: ";
      foreach ($numbers as $n) {
         echo "$n  ";
      }
    } myfunction(5, 12, 9, 23, 8, 41); ?>

    Output

    It will generate the following output −

    First number: 5
    Remaining numbers: 12  9  23  8  41
    

    Variadic Functions

    It is possible to process a variable number of arguments to a function, even without the “…” syntax. PHP has built_in functions like func_num_args(), func_get_arg() and func_get_args(), which can be used with similar result.

    • func_num_args() − Returns the number of arguments passed to the function.
    • func_get_arg() − Returns an item from the argument list
    • func_get_args() − Returns an array comprising a function’s argument list

    Example

    The above example of variable arguments can be rewritten with these functions as below −

    <?php
       function myfunction() {
    
      $sum = 0;
      foreach (func_get_args() as $n) {
         $sum += $n;
      }
      return $sum;
    } echo myfunction(5, 12, 9, 23, 8, 41); ?>

    Output

    It will produce the following output −

    98
    

    Example

    This program prints all the numbers passed to the function −

    <?php
       function myfunction() {
    
      $len = func_num_args();
      echo "Numbers : ";
      $i=0;
      for ($i=0; $i&lt;$len; $i++)
      echo func_get_arg($i) . " ";
    } myfunction(5, 12, 9, 23, 8, 41); ?>

    Output

    It will produce the following output −

    Numbers : 5 12 9 23 8 41
  • Named Arguments

    The feature of Named Arguments has been introduced in PHP with the version 8.0. It is an extension of the existing mechanism of passing positional arguments to a function while calling.

    By default, values of passed arguments are copied to the corresponding formal arguments at the same position. This feature of named arguments in PHP makes it possible to pass the value based on the parameter name instead of the position.

    Example with Positional Arguments

    If we have a function defined as follows −

    functionmyfunction($x,$y){
       statement1;
       statement2;...}

    and it is called as −

    myfunction(10,20);

    In this case, the values are passed to the variables “x” and “y” in the order of declaration. It means, the first value to the first argument, second value to second argument and so on. The variables “x” and “y” are positional arguments.

    To pass the values by named arguments, specify the parameter name to which argument the value is to be passed. The name of the parameter is the name of formal argument without the “$” symbol. The value to be passed is put in front of the “:” symbol.

    myfunction(x:10,y:20);

    Example with Named Arguments

    Here is the code that demonstrates how you can use named arguments in PHP −

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

    Output

    It will produce the following output −

    x = 10  y = 20
    

    Using named arguments makes it possible to pass the values in any order, and not necessarily in the same order in which the arguments are declared in the function definition. We can call myfunction() as shown below and it will produce the same result.

    myfunction(y:20,x:10);

    With this feature, the arguments become order-independent and self-documenting. It also makes it possible to skip the arguments with default values arbitrarily.

    Combining Named Arguments with Positional Arguments

    Named arguments can be combined with positional arguments, with the condition that, the named arguments must come after the positional arguments.

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

    Output

    It will generate the following result −

    x = 10  y = 30  z = 20
    

    However, if you try to treat $z as a positional argument,

    myfunction(x:10,y:20,30);

    In this case, PHP will encounter the following error −

    PHP Fatal error:  Cannot use positional argument after 
    named argument in hello.php on line 7
    

    Passing Named Arguments from an Array

    PHP 8.1.0 also introduced another feature that allows using named argument after unpacking the arguments. Instead of providing values to each argument individually, the values in an array an 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

    It will produce the following output −

    x = 10  y = 20  z = 30
    

    Note that passing the same parameter multiple times results in an exception as follows −

    myfunction(x:10,z:20,x:20);

    Error −

    PHP Fatal error:  Uncaught Error: Named parameter $x 
    overwrites previous argument in hello.php:7
    

    Positional Arguments vs Named Arguments

    Positional arguments are passed in the same order as the function parameters. In this the position or order matters. See the example for positional argument −

    <?php  
       def greet(name, age):
    
      print(f"Hello, my name is {name} and I am {age} years old.")
    greet("Amit", 25) ?>

    Output

    It will produce the following output −

    Hello, my name is Amit and I am 25 years old.
    

    While the arguments passed with parameter names are called Named arguments. The position does not matter because you name the arguments.

    <?php  
       greet(name="Amit", age=25)
    ?>

    Output

    It will produce the following output −

    Hello, my name is Amit and I am 25 years old.
    

    Or change the order −

    <?php  
       greet(age=25, name="Amit")
    ?>

    The output for the above code will be the same. So it proves if we change the order of arguments it does not affect the output of the program.

    Passing Arguments by Reference

    Normally, when you pass a variable to a function, PHP makes a copy of it. If you change a variable inside the function, the original value outside the function remains unchanged. But when you pass a reference (with the & symbol), the function uses the original variable rather than a copy. So, if the function changes the variable, it will be reflected outside of the function!

    <?php  
       function updateString(&$str) 
       {
    
      $str .= " updated";
    } $text = "This is just a test string"; updateString($text); echo $text; ?>

    Output

    It will generate the below output −

    This is just a test string updated
    

    It’s useful when you want to update a variable within a function but maintain the change outside of the function. But you have be careful because falsely changing the variable can lead to unexpected outcomes in your program.

  • Default Arguments

    Like most of the languages that support imperative programming, a function in PHP may have one or more arguments that have a default value. As a result, such a function may be called without passing any value to it. If there is no value meant to be passed, the function will take its default value for processing. If the function call does provide a value, the default value will be overridden.

    Function Definition with Default Values

    Here is the way you can define a function with default values −

    functionfun($arg1= val1,$arg2= val2){
       Statements;}

    Different Ways to Call the Function

    The above function can be called in different ways −

    fun();# Function will use defaults for both argumentsfun($x);# Function passes $x to arg1 and uses default for arg2fun($x,$y);# Both arguments use the values passed

    Example 1

    Here we define a function called greeting() with two arguments, both having string as their default values. We call it by passing one string, two strings and without any argument.

    <?php  
       function  greeting($arg1="Hello", $arg2="world") {
    
      echo $arg1 . " ". $arg2 . PHP_EOL;
    } greeting(); greeting("Thank you"); greeting("Welcome", "back"); greeting("PHP"); ?>

    Output

    It will produce the following output −

    Hello world
    Thank you world
    Welcome back
    PHP world
    

    Example 2

    You can define a function with only some of the arguments with default value, and the others to which the value must be passed.

    <?php  
       function  greeting($arg1, $arg2="World") {
    
      echo $arg1 . " ". $arg2 . PHP_EOL;
    } # greeting(); ## This will raise ArgumentCountError greeting("Thank you"); greeting("Welcome", "back"); ?>

    Output

    It will produce the below result −

    Thank you World
    Welcome back
    

    The first call (without argument) raises ArgumentCountError because you must pass value for the first argument. If only one value is passed, it will be used by the first argument in the list.

    However, if you declare arguments with default before arguments without defaults, such function can be only called if values for both are passed. You cannot have a situation where the first argument uses the default, and the second using the passed value.

    The greeting() function now has $arg1 with default and $arg2 without any default value.

    functiongreeting($arg1="Hello",$arg2){echo$arg1." ".$arg2.PHP_EOL;}

    If you pass a string “PHP” −

    greeting("PHP");

    with the intension to print the result as “Hello PHP”, the following error message will be displayed.

    PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function 
    greeting(), 1 passed in hello.php on line 10 and exactly 2 expected
    

    Example 3

    Let’s define a function percent() that calculates the percentage of marks in three subjects.

    Assuming that the marks in each subject are out of 100, the $total argument in the function definition is given a default value as 300.

    <?php
       function  percent($p, $c, $m, $ttl=300) {
    
      $per = ($p+$c+$m)*100/$ttl;
      echo "Marks obtained: \n";
      echo "Physics = $p Chemistry = $c Maths = $m \n";
      echo "Percentage = $per \n";
    } percent(50, 60, 70); ?>

    Output

    It will generate the following result −

    Marks obtained: 
    Physics = 50 Chemistry = 60 Maths = 70 
    Percentage = 60
    

    However, if the maximum marks in each subject is 50, then you must pass the fourth value to the function, otherwise the percentage will be calculated out of 300 instead of 150.

    <?php
       function  percent($p, $c, $m, $ttl=300) {
    
      $per = ($p+$c+$m)*100/$ttl;
      echo "Marks obtained: \n";
      echo "Physics = $p Chemistry = $c Maths = $m \n";
      echo "Percentage = $per \n";
    } percent(30, 35, 40, 150); ?>

    Output

    It will produce the following output −

    Marks obtained: 
    Physics = 30 Chemistry = 35 Maths = 40 
    Percentage = 70
  • Call by Reference

    PHP uses the “call by value” mechanism, by default, for passing arguments to a function. If the arguments within the function are changed, the changes do not reflect outside of the function. To allow a function to modify its arguments, the “call by reference” mechanism must be used.

    In PHP, a reference variable acts as an “alias” to the original or host variable so that both of them can read and write a single value. In other words, variables of two different names can access to the same value and they behave as if they are the same variable.

    The following PHP script will help in understanding what references are. Here, $var is a normal string variable. We declare $var1 as a reference to $var, append “&” symbol to the latter.

    $var="Hello";$var1=&$var;

    When we say that $var1 is an alias or reference of $var, it means any change in its value will also change the value of $var, and vice versa.

    Example of Call by Reference

    The following another example, which demonstrates how “call by reference” works in PHP −

    <?php  
       $var = "Hello";
       $var1 = &$var;
    
       $var1 = "Hello World";
       echo "var=$var var1=$var1" . PHP_EOL;
    
       $var = "How are you?";
       echo "var=$var var1=$var1" . PHP_EOL;
    ?>

    Output

    It will generate the following output −

    var=Hello World var1=Hello World
    var=How are you? var1=How are you?
    

    Calling a PHP Function by Reference

    To call a function by reference, you need to declare the formal arguments with name prefixed by “&” symbol.

    functioncallref(&$arg1,&$arg2){
       Statements;}

    The call to the function is just as in “call by value” method.

    callref($x,$y);

    When the function is invoked, $arg1 becomes a reference to $x and $arg2 becomes a reference to $y.

    If, inside the function body, the value of $arg1 or $arg2 (or both) changes, it also causes the values of $x and $y to change.

    Example

    Let us have a look at the following example −

    <?php  
       function  change_name(&$nm) {
    
      echo "Initially the name is $nm" . PHP_EOL;
      $nm = $nm."_new";
      echo "This function changes the name to $nm" . PHP_EOL;
    } $name = "John"; echo "My name is $name" . PHP_EOL; change_name($name); echo "My name now is $name" . PHP_EOL; ?>

    The variable $name is passed to the function change_name(). A reference variable &$nm becomes its reference variable. Any change in $nm is reflected in $name outside the function.

    Output

    It will produce the below output −

    My name is John
    Initially the name is John
    This function changes the name to John_new
    My name now is John_new
    

    Swapping Two Variables

    In the following PHP code, we call a function by passing the arguments by value. The function attempts to swap their values.

    Inside the function, their values are changed, but this swap doesnt reflect in the actual arguments after the execution of the function.

    When the same function is called by passing the arguments by reference, the swap effect is reflected in the actual arguments as well.

    <?php  
       function  swap_value($a, $b) {
    
      echo "Initial values a = $a b = $b \n";
      $c = $a; $a = $b; $b = $c;
      echo "Swapped values a = $a b = $b \n";
    } $x = 10; $y =20; echo "Actual arguments x = $x y = $y \n\n"; swap_value($x, $y); echo "Actual arguments do not change after the function: \n"; echo "x = $x y = $y \n\n"; function swap_ref(&$a, &$b) {
      echo "Initial values a = $a b = $b \n";
      $c = $a; $a = $b; $b = $c;
      echo "Swapped values a = $a b = $b \n";
    } swap_ref($x, $y); echo "Actual arguments get changed after the function: \n"; echo "x = $x y = $y"; ?>

    Output

    It will produce the following output −

    Actual arguments x = 10 y = 20 
    
    Initial values a = 10 b = 20 
    Swapped values a = 20 b = 10 
    Actual arguments do not change after the function: 
    x = 10 y = 20 
    
    Initial values a = 10 b = 20 
    Swapped values a = 20 b = 10 
    Actual arguments get changed after the function: 
    x = 20 y = 10
    

    Return by Reference

    Just as a function in PHP can accept arguments by reference, it can also return a reference. To define a function that returns a reference, prefix the name of the function by “&” symbol.

    Example

    The following code shows the example of a function returning a reference. It returns $x, which is a local static variable inside myfunction(). Since “&” symbol is prepended to it, $a (the variable that stores the return value) becomes a reference to &x. As a result, any change in $a will also change the value of $x.

    <?php
       function &myfunction(){
    
      static $x=10;
      echo "x Inside function: $x \n";
      return $x;
    } $a = &myfunction(); echo "Returned by Reference: $a \n"; $a=$a+10; $a = &myfunction(); ?>

    Output

    It will produce the following outcome −

    x Inside function: 10 
    Returned by Reference: 10 
    x Inside function: 20