Category: PHP

  • $_POST

    The $_POST variable in PHP is a super global array that collects form data after submitting an HTML form using the POST method. It is particularly useful for securely sending data and receiving user input.

    What is $_POST?

    $_POST is a built-in PHP array. It stores data received from an HTML form using the POST method.This data is not visible in the URL, making it more secure than the GET method.

    Syntax

    Here is the syntax we can use to define $_POST −

    $_POST['key']

    Here ‘key’ is the name of the form input field.

    Key Points about $_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.

    • $_POST is a superglobal variable, which means it can be accessed from any point in the script without being marked global.
    • Associative array of key-value pairs.
    • POST data is not displayed in the URL, making it more secure for sensitive information like as passwords or personal details.
    • It is compatible with forms that employ URLEncoded or multipart/form-data content.
    • $HTTP_POST_VARS is an old version of $_POST that should not be used.
    • The simplest way to transmit data to the server is to modify the HTML form’s method attribute to POST.

    Example: HTML Form (hello.html)

    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['first_name'] . "&lt;br /&gt; " . 
      "Last Name: " . $_POST['last_name'] . "&lt;/h3&gt;";
    ?></body></html>

    It will produce the following output −

    PHP $ POST 3
  • $_REQUEST

    PHP uses a special variable called $_REQUEST to collect data from forms. It can save data sent using GET, POST or COOKIE methods. This makes it easy to get user input and removes the need to think about how the data is transmitted. The $_REQUEST operates according to the parameters in the “php.ini” file, including the request_order setting. This parameter controls the order in which PHP looks for GET, POST and COOKIE data.

    If you run a PHP script from the command line, the command line parameters will not be in the $_REQUEST array. However, the arguments are filled by the web server in the $_SERVER array.

    Understanding the $_REQUEST Variable in PHP

    • 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['first_name'] . "&lt;br /&gt;" 
      . "Last Name: " . $_REQUEST['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;</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["REQUEST_METHOD"] == "POST")
      echo "&lt;h3&gt;First Name: " . $_REQUEST['first_name'] . "&lt;br /&gt;" 
      . "Last Name: " . $_REQUEST['last_name'] . "&lt;/h3&gt;";
    ?></body></html>

    It will produce the following output −

    PHP $ Request 3

    Security Considerations with $_REQUEST

    As $_REQUEST can collect data from multiple sources (GET, POST, and COOKIE), using it without validation can be unsafe. For example, if you expect form input but someone tampers with cookies, there can be security issues.

    So use $_GET, $_POST or $_COOKIE particularly when you know how data should be sent. Also, to avoid security vulnerabilities like SQL injection and cross-site scripting (XSS), continuously clean and validate user input.

  • $_SERVER

    The $_SERVER is a superglobal in PHP. It includes information about HTTP headers, path, script location, and other things. It is an associative array that contains information about the execution environment and server.

    The majority of these details are filled in by the web server and each server may have different entries. When running PHP scripts from the command line, some of these entries might not be available.

    PHP also generates additional objects using request headers. The header name, which is in uppercase and has underscores instead of hyphens, is followed by the term “HTTP_” for these items.

    Key Points about the $_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.

    Server Variables

    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
    9SCRIPT_FILENAMEThe absolute path to the currently executing script.
    10HTTP_HOSTThe contents of the Host header from the current request.
    11SCRIPT_NAMEContains the path of the current script relative to the document root.
    12REQUEST_URIThe URI that was given to access the page, including the query string.
    13HTTPSSet to ‘on’ if the request was made over HTTPS, otherwise not set.
    14SERVER_PROTOCOLThe name and version of the information protocol used, like HTTP/1.1 or HTTP/2.
    15GATEWAY_INTERFACEThe version of the CGI specification that the server uses, like CGI/1.1.

    Example

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

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

    Access Global Variables with $GLOBALS

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

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

    Output

    It will produce the following outcome −

    Hello
    100
    123
    

    Global vs Local Variables Using $GLOBALS

    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.

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

    Output

    It will produce the following result −

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

    Modify Global Variables

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

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

    Output

    It will produce the below 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)
    

    Read-Only $GLOBALS

    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 wont change $a to 2.

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

    Output

    It will generate the following output −

    int(1)
    

    Update Global Variables Inside a Function

    In the following example, the global variable $counter will be updated directly in the function with the help of $GLOBALS. Each function call increments the value by 1.

    <?php
       $counter = 0;
    
       function incrementCounter() {
    
      $GLOBALS['counter']++;
    } incrementCounter(); incrementCounter(); incrementCounter(); echo "Counter value: " . $counter; ?>

    Output

    Following is the output of the above code −

    Counter value: 3
    

    Use $GLOBALS in Nested Functions

    In the following example, we are using the $GLOBALS inside a nested function. So using this example you can use global variables even inside nested functions.

    <?php
       $var = "Hello";
    
       function outerFunction() {
    
      function innerFunction() {
         echo $GLOBALS['var'] . " from inner function!";
      }
      innerFunction();
    } outerFunction(); ?>

    Output

    Following is the output of the above code −

    Hello from inner function!
    

    Store Arrays in Global Variables

    In the following example, the $GLOBALS lets you directly change arrays stored as global variables. The function mentioned in our example adds new items to the array.

    <?php
       $var = array("Apple", "Banana");
    
       function addFruit($fruit) {
    
      $GLOBALS['var'][] = $fruit;
    } addFruit("Orange"); addFruit("Grapes"); print_r($var); ?>

    Output

    Following is the output of the above code −

    Array
    (
       [0] => Apple
       [1] => Banana
       [2] => Orange
       [3] => Grapes
    )
  • $_SESSION

    One of the superglobal variables in PHP, $_SESSION is an associative array of session variables available in the current script. $HTTP_SESSION_VARS also contains the same information, but it is not a superglobal, and it has now been deprecated.

    What is a Session?

    A Session is an alternative way to make data accessible across the pages of an entire website. It is the time duration between the time a user establishes a connection with a server and the time the connection is terminated. During this interval, the user may navigate to different pages. Many times, it is desired that some data is persistently available across the pages. This is facilitated by session variables.

    A session creates a file in a temporary directory on the server where the registered session variables and their values are stored. This data will be available to all the pages on the site during that visit.

    The server assigns a unique SESSION_ID to each session. Since HTTP is a stateless protocol, data in session variables is automatically deleted when the session is terminated.

    How Sessions Work?

    Here is the way how sessions work −

    • The server assigns a unique SESSION_ID to each user.
    • This ID is stored in a temporary file on the server.
    • The session data is accessible from all pages until the session is terminated.

    Starting a Session

    In order to enable access to session data, the session_start() function must be invoked. session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

    session_start(array$options=[]):bool

    This function returns true if a session was successfully started, else it returns false.

    Creating and Using Session Variables

    To create a new session variable, add a key-value pair in the $_SESSION array −

    $_SESSION["var"]=value;

    To read back the value of a session variable, you can use echo/print statements, or var_dump() or print_r() functions.

    echo$_SESSION["var"];

    To obtain the list of all the session variables in the current session, you can use a foreach loop to traverse the $_SESSION −

    foreach($_SESSIONas$key=>$val)echo$key."=>".$val;

    Deleting Session Variables

    To manually clear all the session data, there is session_destroy() function. A specific session variable may also be released by calling the unset() function.

    unset($_SESSION["var"]);

    List of Session Functions

    In PHP, there are many built-in functions for managing the session data.

    Session FunctionsDescription
    session_abortDiscard session array changes and finish session
    session_cache_expireReturn current cache expire
    session_cache_limiterGet and/or set the current cache limiter
    session_commitAlias of session_write_close
    session_create_idCreate new session id
    session_decodeDecodes session data from a session encoded string
    session_destroyDestroys all data registered to a session
    session_encodeEncodes the current session data as a session encoded string
    session_gcPerform session data garbage collection
    session_get_cookie_paramsGet the session cookie parameters
    session_idGet and/or set the current session id
    session_is_registeredFind out whether a global variable is registered in a session
    session_module_nameGet and/or set the current session module
    session_nameGet and/or set the current session name
    session_regenerate_idUpdate the current session id with a newly generated one
    session_register_shutdownSession shutdown function
    session_registerRegister one or more global variables with the current session
    session_resetRe-initialize session array with original values
    session_save_pathGet and/or set the current session save path
    session_set_cookie_paramsSet the session cookie parameters
    session_set_save_handlerSets user-level session storage functions
    session_startStart new or resume existing session
    session_statusReturns the current session status
    session_unregisterUnregister a global variable from the current session
    session_unsetFree all session variables
    session_write_closeWrite session data and end session

    Example: Managing User Data with PHP Sessions

    The following PHP script renders an HTML form. The form data is used to create three session variables. A hyperlink takes the browser to another page, which reads back the session variables.

    Save this code as “test.php” in the document root folder, and open it in a client browser. Enter the data and press the Submit button.

    <html><head><title>PHP Sessions: How to Use $_SESSION to Manage User Data</title><meta name="keywords" content="PHP Sessions, PHP $_SESSION, Manage User Data in PHP, PHP session_start, session variables, PHP session tutorial"></head><body><form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"><h3>User's ID: <input type="text" name="ID"/></h3><h3>Your Name: <input type="text" name="name"/></h3><h3>Enter Age: <input type="text" name="age"/></h3><input type="submit" value="Submit"/></form><?php
    
      session_start();
      if ($_SERVER["REQUEST_METHOD"] == "POST") {
         $_SESSION['UserID'] = $_POST['ID'];
         $_SESSION['Name'] = $_POST['name'];
         $_SESSION['age'] = $_POST['age'];
      }
      echo "Following Session Variables Created: \n";
      foreach ($_SESSION as $key=&gt;$val)
      echo "&lt;h3&gt;" . $key . "=&gt;" . $val . "&lt;/h3&gt;";
      echo "&lt;br/&gt;" . '&lt;a href="hello.php"&gt;Click Here&lt;/a&gt;';
    ?></body></html>

    When you click the “Submit” button, it will show a list of all the session variables created −

    PHP $ SESSION 1

    Next, have the following script in the “hello.php” file and save it.

    <?php
    session_start();
       echo "<h2>Following Session variables Read:</h2>";
       foreach ($_SESSION as $key=>$val)
       echo "<h3>" . $key . "=>" . $val . "</h3>";
    ?>

    Now, follow the link on the “test.php” page to navigate to “hello.php”. It will show the session variables that are read −

    PHP $ SESSION 2
  • 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!