Author: saqibkhan

  • $_GET

    $_GET is one of the superglobals in PHP. It is an associative array of variables passed to the current script via the query string appended to the URL of HTTP request. Note that the array is populated by all requests with a query string in addition to GET requests.

    $HTTP_GET_VARS contains the same initial information, but that has now been deprecated.

    By default, the client browser sends a request for the URL on the server by using the HTTP GET method. A query string attached to the URL may contain key value pairs concatenated by the “&” symbol. The $_GET associative array stores these key value pairs.

    Save the following script in the document folder of Apache server. If you are using XAMPP server on Windows, place the script as “hello.php” in the “c:/xampp/htdocs” folder.

    <?php
       echo "<h3>First Name: " . $_REQUEST['first_name'] . "<br />" . 
       "Last Name: " . $_REQUEST['last_name'] . "</h3>";
    ?>

    Start the XAMPP server, and enter “http://localhost/hello.php?first_name=Mukesh&last_name=Sinha” as the URL in a browser window. You should get the following output −

    PHP $ GET 1

    The $_GET array is also populated when a HTML form data is submitted to a URL with GET action.

    Under the document root, save the following script as “hello.html” −

    <html><body><form action="hello.php" method="get"><p>First Name: <input type="text" name="first_name"/></p><p>Last Name: <input type="text" name="last_name" /></p><input type="submit" value="Submit" /></form></body></html>

    In your browser, enter the URL “http://localhost/hello.html” −

    PHP $ GET 2

    You should get a similar output in the browser window −

    PHP $ GET 3

    In the following example, htmlspecialchars() is used to convert characters in HTML entities −

    CharacterReplacement
    & (ampersand)&amp;
    ” (double quote)&quot;
    ‘ (single quote)&#039; or &apos;
    < (less than)&lt;
    > (greater than)&gt;

    Assuming that the URL in the browser is “http://localhost/hello.php?name=Suraj&age=20” −

    <?php
       echo  "Name: " . htmlspecialchars($_GET["name"]) . "";
       echo  "Age: " . htmlspecialchars($_GET["age"]) . "<br/>";
    ?>

    It will produce the following output −

    Name: Suraj
    Age: 20
    
  •  $_POST

    $_POST is one of the predefined or superglobal variables in PHP. It is an associative array of key-value pairs passed to a URL by the HTTP POST method that uses URLEncoded or multipart/form-data content-type in the request.

    • $HTTP_POST_VARS also contains the same information as $_POST, but is not a superglobal, and now been deprecated.
    • The easiest way to send data to a server with POST request is specifying the method attribute of HTML form as POST.

    Assuming that the URL in the browser is “http://localhost/hello.php”, method=POST is set in a HTML form “hello.html” as below −

    <html><body><form action="hello.php" method="post"><p>First Name: <input type="text" name="first_name"/></p><p>Last Name: <input type="text" name="last_name" /></p><input type="submit" value="Submit" /></form></body></html>

    The “hello.php” script (in the document root folder) for this exercise is as follows:

    <?php
       echo "<h3>First name: " . $_POST['first_name'] . "<br /> " . 
       "Last Name: " . $_POST['last_name'] . "</h3>";
    ?>

    Now, open http://localhost/hello.html in your browser. You should get the following output on the screen −

    PHP $ POST 1

    As you press the Submit button, the data will be submitted to “hello.php” with the POST method.

    PHP $ POST 2

    You can also mix the HTML form with PHP code in hello.php, and post the form data to itself using the “PHP_SELF” variable −

    <html><body><form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"><p>First Name: <input type="text" name="first_name"/></p><br /><p>Last Name: <input type="text" name="last_name" /></p><input type="submit" value="Submit" /></form><?php
    
      echo "&lt;h3&gt;First Name: " . $_POST&#91;'first_name'] . "&lt;br /&gt; " . 
      "Last Name: " . $_POST&#91;'last_name'] . "&lt;/h3&gt;";
    ?></body></html>

    It will produce the following output −

    PHP $ POST 3
  • $_REQUEST

    In PHP, $_REQUEST is a superglobal variable. It is an associative array which is a collection of contents of $_GET, $_POST and $_COOKIE variables.

    • The settings in your “php.ini” file decides the composition of this variable.
    • One of the directives in “php.ini” is request_order, which decides the order in which PHP registers GET, POST and COOKIE variables.
    • The presence and order of variables listed in this array is defined according to the PHP variables_order.
    • If a PHP script is run from the command line, the argc and argv variables are not included in the $_REQUST array because their values are taken from the $_SERVER array, which in turn is populated by the web server.

    $_REQUEST with GET Method

    Save the following script in the document folder of the Apache server. If you are using XAMPP server on Windows, place the script as “hello.php” in the “c:/xampp/htdocs” folder.

    <html><body><?php
    
      echo "&lt;h3&gt;First Name: " . $_REQUEST&#91;'first_name'] . "&lt;br /&gt;" 
      . "Last Name: " . $_REQUEST&#91;'last_name'] . "&lt;/h3&gt;";
    ?></body></html>

    Start the XAMPP server and enter http://localhost/hello.php?first_name=Amar&last_name=Sharma as the URL in a browser window.

    You should get the output as −

    PHP $ Request 1

    $_REQUEST with POST Method

    Under the document root, save the following script as “hello.html”.

    <html><body><form action="hello.php" method="post">
    
      First Name: &lt;input type="text" name="first_name" /&gt;&lt;br /&gt;
      Last Name: &lt;input type="text" name="last_name" /&gt;&lt;input type="submit" value="Submit" /&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    In your browser, enter the URL "http://localhost/hello.html". You should get the similar output in the browser window.

    PHP $ Request 2

    You may also embed the PHP code inside the HTML script and POST the form to itself with the PHP_SELF variable −

    <html><body><form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"><p>First Name: <input type="text" name="first_name" /></p><p>Last Name: <input type="text" name="last_name" /></p><input type="submit" value="Submit" /></form><?php
    
      if ($_SERVER&#91;"REQUEST_METHOD"] == "POST")
      echo "&lt;h3&gt;First Name: " . $_REQUEST&#91;'first_name'] . "&lt;br /&gt;" 
      . "Last Name: " . $_REQUEST&#91;'last_name'] . "&lt;/h3&gt;";
    ?></body></html>

    It will produce the following output −

    PHP $ Request 3
  •  $_SERVER

    $_SERVER is a superglobal in PHP. It holds information regarding HTTP headers, path and script location, etc.

    • $_SERVER is an associative array and it holds all the server and execution environment related information.
    • Most of the entries in this associative array are populated by the web server. The entries may change from one web server to other, as servers may omit some, or provide others.
    • For a PHP script running on the command line, most of these entries will not be available or have any meaning.
    • PHP will also create additional elements with values from request headers. These entries will be named “HTTP_” followed by the header name, capitalized and with underscores instead of hyphens.
    • For example, the “Accept-Language” header would be available as $_SERVER[‘HTTP_ACCEPT_LANGUAGE’].
    • PHP versions prior to 5.4.0 had $HTTP_SERVER_VARS which contained the same information but it has now been removed.

    The following table lists some of the important server variables of the $_SERVER array followed by the description of their values.

    Sr.NoServer Variables & Description
    1PHP_SELFStores filename of currently executing script.
    2SERVER_ADDRThis property of array returns the IP address of the server under which the current script is executing.
    3SERVER_NAMEName of server host under which the current script is executing. In case of a server running locally, localhost is returned.
    4QUERY_STRINGA query string is the string of key value pairs separated by the “&” symbol and appended to the URL after the “?” symbol.For example, http://localhost/testscript?name=xyz&age=20 URL returns trailing query string
    5REQUEST_METHODHTTP request method used for accessing a URL, such as POST, GET, POST, PUT or DELETE.In the above query string example, a URL attached to query string with the “?” symbol requests the page with GET method
    6DOCUMENT_ROOTReturns the name of the directory on the server that is configured as the document root.On XAMPP apache server, it returns htdocs as the name of document root c:/xampp/htdocs
    7REMOTE_ADDRIP address of the machine from where the user is viewing the current page.
    8SERVER_PORTPort number on which the web server is listening to the incoming request. Default is 80

    Example

    The following script invoked from document root of XAMPP server lists all the server variables −

    Open Compiler

    <?php
       foreach ($_SERVER as $k=>$v)
       echo $k . "=>" . $v . "\n";
    ?>

    It will produce the following output −

    MIBDIRS=>C:/xampp/php/extras/mibs
    MYSQL_HOME=>\xampp\mysql\bin
    OPENSSL_CONF=>C:/xampp/apache/bin/openssl.cnf
    PHP_PEAR_SYSCONF_DIR=>\xampp\php
    PHPRC=>\xampp\php
    TMP=>\xampp\tmp
    HTTP_HOST=>localhost
    HTTP_CONNECTION=>keep-alive
    HTTP_SEC_CH_UA=>"Chromium";v="116", "Not)
    A;Brand";v="24", "Google Chrome";v="116"
    HTTP_SEC_CH_UA_MOBILE=>?0
    HTTP_SEC_CH_UA_PLATFORM=>"Windows"
    HTTP_DNT=>1
    HTTP_UPGRADE_INSECURE_REQUESTS=>1
    HTTP_USER_AGENT=>Mozilla/5.0 (Windows NT 10.0; Win64; x64)
     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36
    HTTP_ACCEPT=>text/html,application/xhtml+xml,application/xml;
    q=0.9,image/avif,image/webp,image/apng,*/*;
    q=0.8,application/signed-exchange;v=b3;q=0.7
    HTTP_SEC_FETCH_SITE=>none
    HTTP_SEC_FETCH_MODE=>navigate
    HTTP_SEC_FETCH_USER=>?1
    HTTP_SEC_FETCH_DEST=>document
    HTTP_ACCEPT_ENCODING=>gzip, deflate, br
    HTTP_ACCEPT_LANGUAGE=>en-US,en;q=0.9,mr;q=0.8
    PATH=>C:\Python311\Scripts\;
    C:\Python311\;C:\WINDOWS\system32;
    C:\WINDOWS;C:\WINDOWS\System32\Wbem;
    C:\WINDOWS\System32\WindowsPowerShell\v1.0\;
    C:\WINDOWS\System32\OpenSSH\;C:\xampp\php;
    C:\Users\user\AppData\Local\Microsoft\WindowsApps;
    C:\VSCode\Microsoft VS Code\bin
    SystemRoot=>C:\WINDOWS
    COMSPEC=>C:\WINDOWS\system32\cmd.exe
    PATHEXT=>.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW
    WINDIR=>C:\WINDOWS
    SERVER_SIGNATURE=>
    Apache/2.4.56 (Win64) OpenSSL/1.1.1t PHP/8.0.28 Server at localhost Port 80
    
    SERVER_SOFTWARE=>Apache/2.4.56 (Win64) OpenSSL/1.1.1t PHP/8.0.28
    SERVER_NAME=>localhost
    SERVER_ADDR=>::1
    SERVER_PORT=>80
    REMOTE_ADDR=>::1
    DOCUMENT_ROOT=>C:/xampp/htdocs
    REQUEST_SCHEME=>http
    CONTEXT_PREFIX=>
    CONTEXT_DOCUMENT_ROOT=>C:/xampp/htdocs
    SERVER_ADMIN=>postmaster@localhost
    SCRIPT_FILENAME=>C:/xampp/htdocs/hello.php
    REMOTE_PORT=>54148
    GATEWAY_INTERFACE=>CGI/1.1
    SERVER_PROTOCOL=>HTTP/1.1
    REQUEST_METHOD=>GET
    QUERY_STRING=>
    REQUEST_URI=>/hello.php
    SCRIPT_NAME=>/hello.php
    PHP_SELF=>/hello.php
    REQUEST_TIME_FLOAT=>1694802456.9816
    REQUEST_TIME=>1694802456
    
  • $GLOBALS

    $GLOBALS is one of the “superglobal” or “automatic global” variables in PHP. It is available in all scopes throughout a script. There is no need to do “global $variable;” to access it within functions or methods.

    $GLOBALS is an associative array of references to all globally defined variables. The names of variables form keys and their contents are the values of an associative array.

    Example

    This example shows $GLOBALS array containing the name and contents of global variables −

    Open Compiler

    <?php
       $var1="Hello";
       $var2=100;
       $var3=array(1,2,3);
    
       echo $GLOBALS["var1"] . "\n";
       echo $GLOBALS["var2"] . "\n";
       echo implode($GLOBALS["var3"]) . "\n";
    ?>

    It will produce the following output −

    Hello
    100
    123
    

    Example

    In the following example, $var1 is defined in the global namespace as well as a local variable inside the function. The global variable is extracted from the $GLOBALS array.

    Open Compiler

    <?php
       function myfunction() {
    
      $var1="Hello PHP";
      echo "var1 in global namespace: " . $GLOBALS&#91;'var1']. "\n";
      echo "var1 as local variable: ". $var1;
    } $var1="Hello World"; myfunction(); ?>

    It will produce the following output −

    var1 in global namespace: Hello World
    var1 as local variable: Hello PHP
    

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

    Example

    Prior to PHP version 8.1.0, global variables could be modified by a copy of $GLOBALS array.

    Open Compiler

    <?php
       $a = 1;
       $globals = $GLOBALS; 
       $globals['a'] = 2;
       var_dump($a);
    ?>

    It will produce the following output −

    int(1)
    

    Here, $globals is a copy of the $GLOBALS superglobal. Changing an element in the copy, with its key as “a” to 2, actually changes the value of $a.

    It will produce the following output −

    int(2)
    

    Example

    As of PHP 8.1.0, $GLOBALS is a read-only copy of the global symbol table. That is, global variables cannot be modified via their copy. The same operation as above won’t change $a to 2.

    Open Compiler

    <?php
       $a = 1;
       $globals = $GLOBALS; 
       $globals['a'] = 2;
       var_dump($a);
    ?>

    It will produce the following output −

    int(1)
    
  • Superglobals

    The PHP parser populates the current script with a number of predefined variables in its global namespace. The predefined variables are known as “PHP superglobals“.

    • Any user defined variable declared outside of any function, method, or class also is a global variable. However, to access it, you need to use the global keyword.
    • In contrast, superglobals are always available anywhere in the PHP script, without mentioning them with the global keyword.

    Most of the superglobals in PHP are associative arrays, and the web server populates them. Hence, if a script is run in the command-line environment, some of the superglobals may be empty.

    The list of superglobal variables in PHP includes the following −

    • $GLOBALS
    • $_SERVER
    • $_GET
    • $_POST
    • $_FILES
    • $_COOKIE
    • $_SESSION
    • $_REQUEST
    • $_ENV

    In this chapter, we will have a brief introduction to these superglobal variables in PHP. In the subsequent chapters, we will discuss these superglobal variables in detail.

    $GLOBALS

    It is an associative array of references to all globally defined variables. Names of variables form keys and their contents are values of associative array.

    $_SERVER

    All the server and execution environment related information is available in this associative array.

    PHP versions prior to 5.4.0 contained $HTTP_SERVER_VARS contained the same information but has now been removed.

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

    $_GET

    It is an associative array of variables passed to the current script via query string appended to URL of HTTP request. Note that the array is populated by all requests with a query string in addition to GET requests.

    A query string is a list of all variables and their values in the form var=val and concatenated by the “&” symbol.

    The query string itself is appended to the name of PHP script after the “?” symbol. For example, http://localhost/hello.php?first_name=Amar&last_name=Sharma.

    $_POST

    It is an associative array of key-value pairs passed to a URL by HTTP POST method that uses URLEncoded or multipart/form-data content-type in request.

    $HTTP_POST_VARS also contains the same information as $_POST, but is not a superglobal, and now been deprecated. The easiest way to send data to a server with POST request is specifying the method attribute of HTML form as POST.

    $_FILES

    The variable $_FILES is an associative array containing items uploaded via HTTP POST method. A file is uploaded when a HTML form contains an input element with file type, its enctype attribute set to multipart/form-data, and the method attribute set to HTTP POST method.

    $_COOKIE

    Cookies are text files stored by a server on the client computer and they are kept of use tracking purpose.

    The superglobal $_COOKIE stores variables passed to the current PHP script along with the HTTP request in the form of cookies.

    $_SESSION

    An HTTP session is the time duration between the time a user establishes connection with a server and the time the connection is terminated. During this interval, some data is persistently available across pages in the form of session variables.

    The $_SESSION superglobal is an associative array of session variables available to the current script.

    $_REQUEST

    $_REQUEST is an associative array which is a collection of contents of $_GET, $_POST and $_COOKIE variables.

    The order of these variables is decided by the values of requests_order and varables_order settings in the “php.ini” file.

    $_ENV

    $_ENV is an associative array that stores all the environment variables available to the current script. This array also includes CGI variables in case PHP is running as a server module or CGI processor.

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

    Example

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

    Open Compiler

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

    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.

    Open Compiler

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

    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.

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

    Example

    Take a look at this following example −

    Open Compiler

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

    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.

    Open Compiler

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

    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.

    Open Compiler

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

    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&#91;'x']+$GLOBALS&#91;'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 −

    Open Compiler

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

    This will produce the following result −

    $x inside function is 0. 
    $x outside of function is 4. 
    
  • Arrow Functions

    Arrow functions were introduced in PHP 7.4 version. Arrow functions provide a simpler and more concise syntax for writing anonymous functions. With PHP 7.4, a keyword “fn” has been introduced for defining arrow functions, instead of the conventional use of the “function” keyword.

    fn(argument_list)=> expr
    
    • 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.

    Example

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

    Open Compiler

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

    Example

    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.

    Open Compiler

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

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

    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.

    Open Compiler

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

    Example

    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.

    Open Compiler

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

    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 doesn’t 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.

    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 variable’s name.

    Example

    Take a look at the following example −

    Open Compiler

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

    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.

    Open Compiler

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

    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.

    Open Compiler

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

    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
    

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

    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 −

    Open Compiler

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

    It will produce the following output −

    Marks = 250 Percentage = 83.333333333333