Category: Functions

  • Global Variables

    In PHP, any variable that can be accessed from anywhere in a PHP script is called as a global variable. If the variable is declared outside all the functions or classes in the script, it becomes a global variable.

    While global variables can be accessed directly outside a function, they aren’t automatically available inside a function.

    Key Points About Global Variables

    Here are some key points to keep in mind about global variables −

    • External classes or functions that are defined
    • Accessible globally, but internal operations need particular handling
    • Use the $GLOBALS array or the global keyword to access functions.

    Example

    In the script below, $name is global for the function sayhello().

    <?php
       $name = "Amar";
       function sayhello() {
    
      echo "Hello " . $name;
    } sayhello(); ?>

    Output

    However, the variable is not accessible inside the function. Hence, you will get an error message “Undefined variable $name”.

    Hello 
    PHP Warning: Undefined variable $name in /home/cg/root/93427/main.php on line 5
    

    Example

    To get access within a function, you need to use the “global” keyword before the variable.

    <?php
       $name = "Amar";
       function sayhello() {
    
      GLOBAL $name;
      echo "Hello " . $name;
    } sayhello(); ?>

    Output

    It will produce the following output −

    Hello Amar
    

    If a function accesses a global variable and modifies it, the modified value is available everywhere after the function call is completed.

    Let us change the value of $name inside the sayhello() function and check its value after the function is called.

    Example

    Take a look at this following example −

    <?php
       $name = "Amar";
       function sayhello() {
    
      GLOBAL $name;
      echo "Global variable name: $name" .PHP_EOL;
      $name = "Amarjyot";
      echo "Global variable name changed to: $name" .PHP_EOL;
    } sayhello(); echo "Global variable name after function call: $name" .PHP_EOL; ?>

    Output

    It will produce the following output −

    Global variable name: Amar
    Global variable name changed to: Amarjyot
    Global variable name after function call: Amarjyot
    

    The $GLOBALS Array

    PHP maintains an associative array named $GLOBALS that holds all the variables and their values declared in a global scope. The $GLOBALS array also stores many predefined variables called as superglobals, along with the user defined global variables.

    Any of the global variables can also be accessed inside any function with the help of a regular syntax of accessing an arrow element. For example, the value of the global variable $name is given by $GLOBALS[“name”].

    Example

    In the following example, two global variable $x and $y are accessed inside the addition() function.

    <?php
       $x = 10;
       $y = 20;
    
       function addition() {
    
      $z = $GLOBALS['x']+$GLOBALS['y'];
      echo "Addition: $z" .PHP_EOL;
    } addition(); ?>

    Output

    It will produce the following output −

    Addition: 30
    

    Example

    You can also add any local variable into the global scope by adding it in the $GLOBALS array. Let us add $z in the global scope.

    <?php
       $x = 10;
       $y = 20;
       function addition() {
    
      $z = $GLOBALS['x']+$GLOBALS['y'];
      $GLOBALS['z'] = $z;
    } addition(); echo "Now z is the global variable. Addition: $z" .PHP_EOL; ?>

    Output

    It will produce the following output −

    Now z is the global variable. Addition: 30
    

    Including One PHP Script in Another

    You can include one PHP script in another. Variables declared in the included script are added in the global scope of the PHP script in which it is included.

    Here is “a.php” file −

    <?php
       include 'b.php';
       function addition() {
    
      $z = $GLOBALS['x']+$GLOBALS['y'];
      echo "Addition: $z" .PHP_EOL;
    } addition(); ?>

    It includes “b.php” that has the $x and $y variables, so they become the global variables for the addition() function in “a.php” script.

    <?php
       $x = 10;
       $y = 20;
    ?>

    Global variables are generally used while implementing singleton patterns, and accessing registers in embedded systems and also when a variable is being used by many functions.

  • Local Variables

    Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types −

    • Local Variables
    • Global Variables
    • Static Variables
    • Function Parameters

    Local Variables

    A variable declared in a function is considered local; that is, it can be referenced solely in that function. Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function. You cannot access them outside of the function.

    Consider local variables as private notes. Only the author (function) can read them.

    How Local Variables Work

    When a function is called, PHP creates local variables. When the function ends, PHP deletes the variables. Local variables exist only during the function’s execution.

    Example 1

    Here is the example to show hwo the local variable work in PHP −

    <?php
       $x = 4;
       
       function assignx () { 
    
      $x = 0;
      print "\$x inside function is $x. \n";
    } assignx(); print "\$x outside of function is $x. \n"; ?>

    Output

    This will produce the following result −

    $x inside function is 0. 
    $x outside of function is 4. 
    

    Example 2

    You can use local variables inside a loop also. So check how the local variables work in a for loop.

    <?php
       function countToThree() {
    
      for ($i = 1; $i &lt;= 3; $i++) {
         // Local variable
         echo $i . " "; 
      }
    } countToThree(); ?>

    Output

    Following is the output of the above code −

    1 2 3
    

    Example 3

    In this example, $age is a local variable inside the checkAge() function. The variable is only available inside the function you can’t access it from outside.

    <?php
       function checkAge() {
    
      // Local variable
      $age = 20; 
      if ($age &gt;= 18) {
         echo "You are an adult.";
      } else {
         echo "You are a minor.";
      }
    } checkAge(); ?>

    Output

    Following is the output of the above code −

    You are an adult.
    

    Why Use Local Variables?

    Here are some of the reasons why you should use local variables −

    • Security: Local variables protect data within functions.
    • Memory Management: After use, local variables are deleted to save memory.
    • Avoid conflict: Local variables with the same name in different functions do not interact with each other.

    Important Points to Keep in Mind

    Understanding local variables is important to write PHP code that is secure, efficient, and clean. Here are some key points of local variables you should keep in mind −

    • Local variables are defined inside a function.
    • Only when the function is operating do they exist.
    • When not in use, they are inaccessible.
    • Many functions can use the same variable names without getting any issues.
  • Variable Functions

    PHP Variable Handling Functions are the inbuilt PHP library functions that enable us to manipulate and test php variables in various ways.

    Installation

    There is no installation needed to use PHP variable functions; they are part of the PHP core and comes along with standard PHP installation.

    Runtime Configuration

    This extension has no configuration directives defined in php.ini.

    PHP Variable Handling Functions

    Following table lists down all the functions related to PHP Variable Handling. Here column version indicates the earliest version of PHP that supports the function.

    Sr.NoFunction & DescriptionVersion
    1boolval()Function returns boolean value of a defined variable, i.e, it returns TRUE or FALSE.5.5.0
    2debug_zval_dump()Function is used to dump a string representation of an internal zend value to output.4.2.0
    3doubleval()Function is used to return the float value of a defined variable.4, 5, 7, 8
    4empty()Function is used to check if the defined variable has empty value.4, 5, 7, 8
    5floatval()Function used return the float value of a defined variable.4.2.0, 5, 7, 8
    6get_defined_vars()Function is used to return all the defined variables as an array.4.0.4, 5, 7, 8
    7get_resource_id()Function is used to return an integer identifier for the given resource.8
    8get_resource_type()Function returns the type a resource of the variable defined.4.0.2, 5, 7, 8
    9gettype()Function returns the type of the variable defined.4, 5, 7, 8
    10intval()Function returns integer value of the defined variable.4, 5, 7, 8
    11is_array()Function is used to check if the defined variable is an array.4, 5, 7, 8
    12is_bool()Function is used to check if the defined variable is boolean, i.e, it returns true or false value.4, 5, 7, 8
    13is_callable()Function is used to check if the data in the variable can be called as a function4.0.6, 5, 7, 8
    14is_countable()Function is used to check if the data in the variable is countable.7.3.0, 8
    15is_double()Function is used to check if the variable defined is of the type float4, 5, 7, 8
    16is_float()Function is used to check if the variable defined is an float4, 5, 7, 8
    17is_int()Function is used to check if the variable defined is of the type integer4, 5, 7, 8
    18is_integer()Function is used to check if the variable defined is an integer.4, 5, 7, 8
    19is_iterable()Function is used to check if the data in the variable is an iterable value.7.1.0, 8
    20is_long()Function is used to check if the variable is of the type integer.4, 5, 7, 8
    21is_null()Function checks if the variable has NULL value.4.0.4, 5, 7, 8
    22is_numeric()Function is used to check if the defined variable is numeric or a numeric string.4, 5, 7, 8
    23is_object()Function is used to check if the variable is an object.4, 5, 7, 8
    24is_real()Function is used to check if the defined variable is of the type float or not.4, 5, 7, 8
    25is_resource()Function is used to check if the defined variable is resource.4, 5, 7, 8
    26is_scalar()Function is used to check if the defined variable is scalar.4.0.5, 5, 7, 8
    27is_string()Function is used to check if the defined variable is of the type string.4, 5, 7, 8
    28isset()Function is used to check if a variable is declared and set.4, 5, 7, 8
    29print_r()Function used to represent or print the data of a variable into a readable format.4, 5, 7, 8
    30serialize()Function used to convert the data of a variable into a storable representation, so that the data can be stored in a file, a memory buffer4, 5, 7, 8
    31settype()Function is used to set a variable into a specific type.4, 5, 7, 8
    32strval()Function is used to return a string value of a variable.4, 5, 7, 8
    33unserialize()Function is used to unserialize the data of a variable. i.e, this function returns actual data of a serialize variable.4, 5, 7, 8
    34unset()Function used unset a variable4, 5, 7, 8
    35var_dump()Function is used to dump information about one or more variables. The information holds type and value of the variable(s).4, 5, 7, 8
    36var_export()Function returns structured information about a variable.4.2.0, 5, 7, 8

  • Arrow Functions

    Arrow functions were added in PHP 7.4 to make it easier and faster to write anonymous functions. Instead of the regular “function” term, you can now type “fn”. The new version simplifies your code, making it cleaner and more readable. Arrow functions are perfect for short, one-line functions because they automatically return the result without the need for an explicit return statement.

    They also inherit variables from the parent scope, so you do not need to pass them separately. Overall, arrow functions are a fantastic addition to PHP, making it faster and easier to write small inline functions.

    Here is the syntax for using the arrow functions in your code −

    fn(argument_list)=> expr
    

    Key Points About Arrow Functions

    Arrow functions have some key points listed below that make them different from regular functions −

    • There is only one expression after the “=>” symbol, and its value is the return value of the arrow function.
    • The arrow function doesn’t have an explicit return statement.
    • Like in the anonymous function, the arrow function is assigned to a variable for it to be called.

    Basic Addition with Arrow Function

    The following example demonstrates how you can use the arrow function in PHP −

    <?php
       $add = fn ($a, $b) => $a + $b;
    
       $x = 10;
       $y = 20; 
       echo " x: $x y: $y Addition: " . $add($x, $y);
    ?>

    It will produce the following output −

    x: 10 y: 20 Addition: 30
    

    Using the Arrow Function as a Callback Function

    We can also use the arrow function as a callback function. Callback functions are used as one of the arguments of another function. The arrow function is executed on the fly and the value of the expression after “=>” becomes the argument of the parent function, which may be either a built-in or a user-defined function.

    In this example, we use an arrow function inside usort() function, a built_in function that sorts an array by values using a user-defined comparison function.

    <?php
       $arr = [10,3,70,21,54];
       usort ($arr, fn ($x , $y) => $x > $y);
    
       foreach ($arr as $x){
    
      echo $x . "\n";
    } ?>

    It will produce the following output −

    3
    10
    21
    54
    70
    

    Accessing Variables from the Parent Scope

    Arrow functions can automatically access variables from the parent scope. Unlike the anonymous functions, the “use” keyword is not necessary for it to act as a closure. When a variable used in the expression is defined in the parent scope, it will be implicitly captured by-value.

    <?php
       $maxmarks=300;
       $percent=fn ($marks) => $marks*100/$maxmarks;
    
       $m = 250;
       echo "Marks = $m Percentage = ". $percent($m);
    ?>

    It will produce the following output −

    Marks = 250 Percentage = 83.333333333333
    

    Nested Arrow Functions

    Arrow functions capture variables by value automatically, even when nested.

    In the following example, an arrow function is defined in the expression part of another arrow function.

    <?php
       $z = 1;
       $fn = fn($x) => fn($y) => $x * $y + $z;
       $x = 5;
       $y = 10; 
       echo "x:$x y:$y \n";
       echo "Result of nested arrow functions: " . ($fn($x)($y));
    ?>

    It will produce the following output −

    x:5 y:10 
    Result of nested arrow functions: 51
    

    Filtering an Array with Arrow Functions

    You can use arrow functions to filter elements in an array very easily. So here is the example below in which we are filtering out the even numbers and showing them in the output.

    <?php
       $numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
       $evenNumbers = array_filter($numbers, fn($n) => $n % 2 === 0);
    
       foreach ($evenNumbers as $num) {
    
      echo $num . " ";
    } ?>

    Output

    Following is the output of the above code −

    2 4 6 8 10
    

    Transform an Array with array_map

    Arrow functions are used to transform an array using array_map. In the following example, we are using array_map() function to change the array into a squared numbers array.

    <?php
       $nums = [1, 2, 3, 4];
       $squared = array_map(fn($n) => $n * $n, $nums);
    
       print_r($squared);
    ?>

    Output

    Following is the output of the above code −

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

    Just like anonymous functions, the arrow function syntax allows arbitrary function signatures, including parameter and return types, default values, variadics, as well as by-reference passing and returning.

  • Anonymous Functions

    What are Anonymous Functions?

    PHP allows defining anonymous functions. Normally, when we define a function in PHP, we usually provide it a name which is used to call the function whenever required. In contrast, an anonymous function is a function that doesnt have any name specified at the time of definition. Such a function is also called closure or lambda function.

    Sometimes, you may want a function for one time use only. The most common use of anonymous functions is to create an inline callback function.

    Anonymous functions are implemented using the Closure class. Closure is an anonymous function that closes over the environment in which it is defined.

    Syntax

    The syntax for defining an anonymous function is as follows −

    $var=function($arg1,$arg2){return$val;};

    Note that there is no function name between the function keyword and the opening parenthesis, and the fact that there is a semicolon after the function definition. This implies that anonymous function definitions are expressions. When assigned to a variable, the anonymous function can be called later using the variables name.

    Example

    Take a look at the following example −

    <?php
       $add = function ($a, $b) {
    
      return "a:$a b:$b addition: " . $a+$b; 
    }; echo $add(5,10); ?>

    Output

    It will produce the following output −

    a:5 b:10 addition: 15
    

    Anonymous Function as a Callback

    Anonymous functions are often used as callbacks. Callback functions are used as one of the arguments of another function. An anonymous function is executed on the fly and its return value becomes the argument of the parent function, which may be either a built-in or a user-defined function.

    Example

    In this example, we use an anonymous function inside the usort() function, a built in function that sorts an array by values using a user-defined comparison function.

    <?php
       $arr = [10,3,70,21,54];
       usort ($arr, function ($x , $y) {
    
      return $x &gt; $y;
    }); foreach ($arr as $x){
      echo $x . "\n";
    } ?>

    Output

    It will produce the following output −

    3
    10
    21
    54
    70
    

    Example

    The following example uses an anonymous function to calculate the cumulative sum after successive numbers in an array. Here, we use the array_walk() function. This function applies a user defined function to each element in the array.

    <?php
       $arr=array(1,2,3,4,5);
       array_walk($arr, function($n){
    
      $s=0;
      for($i=1;$i&lt;=$n;$i++){
         $s+=$i;
      }
      echo "Number: $n Sum: $s". PHP_EOL;
    }); ?>

    Output

    It will produce the following output −

    Number: 1 Sum: 1
    Number: 2 Sum: 3
    Number: 3 Sum: 6
    Number: 4 Sum: 10
    Number: 5 Sum: 15
    

    Anonymous Function as Closure

    Closure is also an anonymous function that can access the variables outside its scope with the help of the “use” keyword.

    Example

    Take a look a the following example −

    <?php
       $maxmarks=300;
       $percent=function ($marks) use ($maxmarks) {
    
      return $marks*100/$maxmarks;
    }; $m = 250; echo "Marks = $m Percentage = ". $percent($m); ?>

    Output

    It will produce the following output −

    Marks = 250 Percentage = 83.333333333333
    

    Static Anonymous Functions

    Anonymous functions can be declared statically. This stops the current class from being automatically connected to them. Objects may not be bound to them during runtime.

    Example

    Here in the below example we are trying to use $this inside a static anonymous function −

    <?php
       class MyClass
       {
    
      function sayHello()
      {
         $myFunction = static function($name) {
               echo "Hello " . $name . "!";
         };
         $myFunction("Aryan");
      }
    } $obj = new MyClass(); $obj->sayHello(); ?>

    Output

    Following is the output of the above code −

    Hello Aryan!
    

  • 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