Category: PHP

  • The “use” Statement

    The “use” keyword in PHP is found to be associated with multiple purposes, such as aliasing, inserting traits and inheriting variables in closures.

    Aliasing

    Aliasing is accomplished with the use operator. It allows you to refer to an external fully qualified name with an alias or alternate name.

    Example

    Take a look at the following example −

    useMy\namespace\myclassas Another;$obj=newAnother;

    You can also have groupped use declaration as follows −

    use some\namespace\{ClassA, ClassB, ClassC asC};usefunction some\namespace\{fn_a, fn_b, fn_c};useconst some\namespace\{ConstA, ConstB, ConstC};

    Traits

    With the help of use keyword, you can insert a trait into a class. A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own.

    Example

    Take a look at the following example −

    <?php
       trait mytrait {
    
      public function hello() {
         echo "Hello World from " . __TRAIT__ .;
      }
    } class myclass {
      use mytrait;
    } $obj = new myclass(); $obj->hello(); ?>

    It will produce the following output −

    Hello World from mytrait
    

    Closures

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

    Example

    Take a look at the following example −

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

  • Expectations

    Expectations are a backwards compatible enhancement to the older assert() function. Expectation allows for zero-cost assertions in production code, and provides the ability to throw custom exceptions when the assertion fails.

    assert() is now a language construct, where the first parameter is an expression as compared to being a string or Boolean to be tested.

    Configuration Directives for assert()

    The following table lists down the configuration directives for the assert() function −

    DirectiveDefault valuePossible values
    zend.assertions11 − generate and execute code (development mode)0 − generate code but jump around it at runtime-1 − do not generate code (production mode)
    assert.exception01 − throw, when the assertion fails, either by throwing the object provided as the exception or by throwing a new AssertionError object if exception was not provided.0 − use or generate a Throwable as described above, but only generates a warning based on that object rather than throwing it (compatible with PHP 5 behaviour)

    Parameters

    • Assertion − The assertion. In PHP 5, this must be either a string to be evaluated or a Boolean to be tested. In PHP 7, this may also be any expression that returns a value, which will be executed and the result is used to indicate whether the assertion succeeded or failed.
    • Description − An optional description that will be included in the failure message, if the assertion fails.
    • Exception − In PHP 7, the second parameter can be a Throwable object instead of a descriptive string, in which case this is the object that will be thrown, if the assertion fails and the assert.exception configuration directive is enabled.

    Return Values

    FALSE if the assertion is false, TRUE otherwise.

    Example

    Take a look at the following example −

    <?php
       ini_set('assert.exception', 1);
       class CustomError extends AssertionError {}
       assert(false, new CustomError('Custom Error Message!'));
    ?>

    It will produce the following output −

    PHP Fatal error:  Uncaught CustomError: Custom Error Message! In test.php:6
    

  • CSPRNG

    The acronym CSPRNG stands for Cryptographically Secure Pseudorandom Number Generator. PHP function library includes many functions that generate random numbers. For example −

    • mt_rand() − Generate a random value via the Mersenne Twister Random Number Generator
    • mt_srand() − Seeds the Mersenne Twister Random Number Generator
    • rand() − Generate a random integer.

    Example

    The following code shows how you can use the function mt_rand() to generate random numbers −

    <?php
       # Generates random integer between the range
       echo "Random integer: " . rand(1,100) . PHP_EOL;
       # Generate a random value via the Mersenne Twister Random Number Generator
       echo "Random number: " . mt_rand(1,100);
    ?>

    It will produce the following output −

    Random integer: 45
    Random number: 86
    

    Note that the output may vary every time the code is executed. However, random numbers generated by these functions are not cryptographically safe, as it is possible to guess their outcome. PHP 7, introduced a couple of functions that generate secure random numbers.

    The following functions which are cryptographically secure, are newly added −

    • random_bytes() − Generates cryptographically secure pseudo-random bytes.
    • random_int() − Generates cryptographically secure pseudo-random integers.

    The random_bytes() Function

    random_bytes() generates an arbitrary-length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors.

    stringrandom_bytes(int$length)

    Parameters

    • length − The length of the random string that should be returned in bytes.

    The function returns a string containing the requested number of cryptographically secure random bytes.

    If an appropriate source of randomness cannot be found, an Exception will be thrown. If invalid parameters are given, a TypeError will be thrown. If an invalid length of bytes is given, an Error will be thrown.

    Example

    Take a look at the following example −

    <?php
       $bytes = random_bytes(5);
       print(bin2hex($bytes));
    ?>

    It may produce the following output (it may differ every time) −

    6a85eec950
    

    The random_int() Function

    random_int() generates cryptographic random integers that are suitable for use where unbiased results are critical.

    intrandom_int(int$min,int$max)

    Parameters

    • min − The lowest value to be returned, which must be PHP_INT_MIN or higher.
    • max − The highest value to be returned, which must be less than or equal to PHP_INT_MAX.

    The function returns a cryptographically secure random integer in the range min to max, inclusive.

    If an appropriate source of randomness cannot be found, an Exception will be thrown. If invalid parameters are given, a TypeError will be thrown. If max is less than min, an Error will be thrown.

    Example

    Take a look at the following example −

    <?php
       print(random_int(100, 999));
       print("\n");
       print(random_int(-1000, 0));
    ?>

    It may produce the following output (it differs every time) −

    495
    -563
    

  • IntlChar

    In PHP7, a new IntlChar class has been introduced. It provides access to a number of utility methods that can be used to access information about Unicode characters. There are a number of static methods and constants in Intl class. They adhere closely to the names and behavior used by the underlying ICU (International Components for Unicode) library.

    Note that you need to enable the Intl extension in the PHP installation in your system. To enable, open php.ini file and uncomment (remove the leading semicolon from the line)

    extension=intl
    

    Some static functions from Intl class are explained with examples as below −

    IntlChar::charAge

    This function gets the “age” of the code point

    publicstaticIntlChar::charAge(int|string$codepoint):?array

    The “age” is the Unicode version when the code point was first designated (as a non-character or for Private Use) or assigned a character.

    Example

    Take a look at the following example −

    <?php
       var_dump(IntlChar::charage("\u{2603}"));
    ?>

    It will produce the following output −

    array(4) {
       [0]=>
       int(1)
       [1]=>
       int(1)
       [2]=>
       int(0)
       [3]=>
       int(0)
    }
    

    IntlChar::charFromName

    The charFromName() function finds Unicode character by name and return its code point value

    publicstaticIntlChar::charFromName(string$name,int$type=IntlChar::UNICODE_CHAR_NAME):?int

    The type parameter sets of names to use for the lookup. Can be any of these constants −

    • IntlChar::UNICODE_CHAR_NAME (default)
    • IntlChar::UNICODE_10_CHAR_NAME
    • IntlChar::EXTENDED_CHAR_NAME
    • IntlChar::CHAR_NAME_ALIAS
    • IntlChar::CHAR_NAME_CHOICE_COUNT

    Example

    Take a look at the following example −

    <?php
       var_dump(IntlChar::charFromName("LATIN CAPITAL LETTER A"));
       var_dump(IntlChar::charFromName("SNOWMAN"));
    ?>

    It will produce the following output −

    int(65)
    int(9731)
    

    IntlChar::charName

    The charName() function retrieves the name of a Unicode character

    publicstaticIntlChar::charName(int|string$codepoint,int$type=IntlChar::UNICODE_CHAR_NAME):?string

    Example

    Take a look at the following example −

    <?php
       var_dump(IntlChar::charName(".", IntlChar::UNICODE_CHAR_NAME));
       var_dump(IntlChar::charName("\u{2603}"));
    ?>

    It will produce the following output −

    string(9) "FULL STOP"
    string(7) "SNOWMAN"
    

    IntlChar::isalpha

    The isalpha() function determines whether the specified code point is a letter character. true for general categories “L” (letters).

    publicstaticIntlChar::isalpha(int|string$codepoint):?bool

    Example

    Take a look at the following example −

    <?php
       var_dump(IntlChar::isalpha("A"));
       var_dump(IntlChar::isalpha("1"));
    ?>

    It will produce the following output −

    bool(true)
    bool(false)
    

    The Intl class defines similar static methods such as isdigit(), isalnum(), isblank(), etc.

    IntlChar::islower

    The islower() function determines whether the specified code point has the general category “Ll” (lowercase letter).

    publicstaticIntlChar::islower(int|string$codepoint):?bool

    Example

    Take a look at the following example −

    <?php
       var_dump(IntlChar::islower("A"));
       var_dump(IntlChar::islower("a"));
    ?>

    It will produce the following output −

    bool(false)
    bool(true)
    

    Similarly, there are functions such as isupper(), istitle(), iswhitespace() etc.

    IntlChar::toupper

    The given character is mapped to its uppercase equivalent.

    publicstaticIntlChar::toupper(int|string$codepoint):int|string|null

    If the character has no uppercase equivalent, the character itself is returned.

    Example

    Take a look at the following example −

    <?php
       var_dump(IntlChar::toupper("A"));
       var_dump(IntlChar::toupper("a"));
    ?>

    It will produce the following output −

    string(1) "A"
    string(1) "A"

  • Filtered unserialize

    In PHP, the built-in function unserialize() is available from PHP version 4 onwards. With PHP 7, a provision to pass a list of allowed classes has been added. This allows the untrusted source to be filtered out. The unserialze() function unserializes the data from only the trusted classes.

    In PHP, serialization means generation of a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure. The built-in serialize() function is used for this purpose.

    serialize(mixed $value): string

    The unserialze() function gives a PHP value from the serialized representation. From PHP 7 onwards, the unserialize() function follows the format below −

    unserialize(string $data, array $options = [ ]): mixed

    The $data parameter is the serialized string which you want to unserialize.

    The $options parameter has been newly introduced. It is an associative array of following keys −

    Sr.NoName & Description
    1allowed_classesan array of class names which should be accepted,orfalse to accept no classes,ortrue to accept all classes.Omitting this option is the same as defining it as true
    2max_depthThe maximum depth of structures permitted during unserialization.

    Example

    Take a look at the following example −

    <?php
       class MyClass { 
    
      var int $x;
      function __construct(int $x) {
         $this-&gt;x = $x;
      }
    } class NewClass {
      var int $y;
      function __construct(int $y) {
         $this-&gt;y = $y;
      }
    } $obj1 = new MyClass(10); $obj2 = new NewClass(20); $sob1 = serialize($obj1); $sob2 = serialize($obj2); // default behaviour that accepts all classes // second argument can be ommited. // if allowed_classes is passed as false, unserialize converts all objects into __PHP_Incomplete_Class object $usob1 = unserialize($sob1 , ["allowed_classes" => true]); // converts all objects into __PHP_Incomplete_Class object except those of MyClass and NewClass $usob2 = unserialize($sob2 , ["allowed_classes" => ["MyClass", "NewClass"]]); echo $usob1->x . PHP_EOL; echo $usob2->y . PHP_EOL; ?>

    It will produce the following output −

    10
    20
    
  • Closure call

    In PHP, a closure is an anonymous function that has access to the variables in the scope in which it was created, even after that scope has closed. You need to specify use keyword in it.

    Closures are objects that encapsulate the function code and the scope in which they were created. With PHP 7, a new closure::call() method was introduced to bind an object scope to a closure and invoke it.

    Methods in the Closure Class

    The Closure class has the following methods including the call() method −

    finalclassClosure{/* Methods */private__construct()publicstaticbind(Closure$closure,?object$newThis,object|string|null$newScope="static"):?ClosurepublicbindTo(?object$newThis,object|string|null$newScope="static"):?Closurepubliccall(object$newThis,mixed...$args):mixedpublicstaticfromCallable(callable$callback):Closure}

    The call() method is a static method of Closure class. It has been introduced as a shortcut the bind() or bindTo() methods.

    The bind() method Duplicates a closure with a specific bound object and class scope while the bindTo() method duplicates the closure with a new bound object and class scope.

    The call() method has the following signature −

    publicClosure::call(object$newThis,mixed...$args):mixed

    The call() method temporarily binds the closure to newThis, and calls it with any given parameters.

    With version prior to PHP 7, the bindTo() method can be used as follows −

    <?php
       class A {
    
      private $x = 1;
    } // Define a closure Pre PHP 7 code $getValue = function() {
      return $this-&gt;x;
    }; // Bind a clousure $value = $getValue->bindTo(new A, 'A'); print($value()); ?>

    The program binds the $getValue which is a closure object, to the object of A class and prints the value of its private variable $x it is 1.

    With PHP 7, the binding is achieved by call() method as shown below −

    <?php
       class A {
    
      private $x = 1;
    } // PHP 7+ code, Define $value = function() {
      return $this-&gt;x;
    }; print($value->call(new A)); ?>
  • Swapping Variables

    PHP doesnt provide any built-in function with which you can swap or interchange values of two variables. However, there are a few techniques which you can use to perform the swap.

    One of the most straightforward approaches is to use a third variable as a temporary place holder to facilitate swapping. Using the arithmetic operators in a specific order also is very effective. You can also use the binary XOR operator for swapping purpose. In this chapter, we shall implement these swapping techniques in PHP

    Temporary Variable

    This is logically the most obvious and the simplest approach. To swap values of “a” and “b”, use a third variable “c”. Assign the value of “a” to “c”, overwrite “a” with existing value of “b” and then set “b” to the earlier value of “a” that was stored in “c”.

    Example

    Take a look at the following example −

    <?php
       $a = 10;
       $b = 20;
       echo "Before swapping - \$a = $a, \$b = $b". PHP_EOL;
       $c = $a; 
       $a = $b;
       $b = $c;
       echo "After swapping - \$a = $a, \$b = $b". PHP_EOL;
    ?>

    It will produce the following output −

    Before swapping - $a = 10, $b = 20
    After swapping - $a = 20, $b = 10
    

    Using addition (+) Operator

    This solution takes the advantage of the fact that subtracting a number from the sum of two numbers gives back the second number. In other words, “sum(a+b) a” is equal to “b” and vice versa.

    Example

    Let us take advantage of this property to swap “a” and “b” −

    <?php
       $a = 10;
       $b = 20;
       echo "Before swapping - \$a = $a, \$b = $b". PHP_EOL;
       $a = $a + $b;
       $b = $a - $b;
       $a = $a - $b;
       echo "After swapping - \$a = $a, \$b = $b". PHP_EOL;
    ?>

    It will produce the following output −

    Before swapping - $a = 10, $b = 20
    After swapping - $a = 20, $b = 10
    

    You can also use the other arithmetic operators subtraction (-), multiplication (*) and division (/) in a similar manner to perform swapping.

    Using list() Function

    The list() function in PHP unpacks the array in separate variables. This helps in our objective of performing swap between two variables. To do that, build an array of “a” and “b”, and then unpack it to “b” and “a” variables to obtain “a” and “b” with interchanged values.

    Example

    Take a look at the following example −

    <?php
       $a = 10;
       $b = 20;
       echo "Before swapping - \$a = $a, \$b = $b". PHP_EOL;
       $arr = [$a, $b];
       list($b, $a) = $arr;
       echo "After swapping - \$a = $a, \$b = $b". PHP_EOL;
    ?>

    It will produce the following output −

    Before swapping - $a = 10, $b = 20
    After swapping - $a = 20, $b = 10
    

    Bitwise XOR

    The bitwise XOR (^) operator can also be used to swap the value of two variables “x” and “y”. It returns 1 when one of two bits at same position in both operands is 1, otherwise returns 0.

    Example

    Take a look at the following example −

    <?php
       $a = 10;
       $b = 20;
       echo "Before swapping - \$a = $a, \$b = $b". PHP_EOL;
       $a = $a ^ $b;
       $b = $a ^ $b;
       $a = $a ^ $b;
       echo "After swapping - \$a = $a, \$b = $b". PHP_EOL;
    ?>

    It will produce the following output −

    Before swapping - $a = 10, $b = 20
    After swapping - $a = 20, $b = 10

  • HTTP Authentication

    In PHP, the header() function is used to send an “Authentication Required” message to the client browser causing it to pop up a Username/Password input window. In fact header() allows you to send any raw HTTP header.

    header(string$header,bool$replace=true,int$response_code=0):void

    The string parameter is passed to the header() function. For example

    header("HTTP/1.1 404 Not Found");

    It is used to figure out the HTTP status code to send.

    You can also use header() function to redirect the browser to another URL.

    Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER array. Only “Basic” and “Digest” authentication methods are supported.

    <?php
    
       /* Redirect browser */
       header("Location: http://www.example.com/"); 
    
       /* Make sure that code below does not get executed when we redirect. */
       exit;
       
    ?>

    The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type, and response_code parameter forces the HTTP response code to the specified value.

    To be able to force he client authentication, you need a .htaccess file in document root folder. Open a new text file, put the following text in it, and save it with .htaccess as its name.

    CGIPassAuth On
    

    Example

    An example script fragment which would force client authentication on a page is as follows −

    <?php
       if (!isset($_SERVER['PHP_AUTH_USER'])) {
    
      header('WWW-Authenticate: Basic realm="My Realm"');
      header('HTTP/1.0 401 Unauthorized');
      echo 'User hits Cancel button';7
      exit;
    } else {
      echo "&lt;p&gt;Hello {$_SERVER['PHP_AUTH_USER']}.&lt;/p&gt;";
      echo "&lt;p&gt;You entered {$_SERVER['PHP_AUTH_PW']} as your password.&lt;/p&gt;";
    } ?>

    Output

    When you visit the script in a browser, it pops up a dialog box as shown −

    PHP HTTP Authentication 1

    Once you click on the sign in button, there may be a backend script to authenticate the login credentials. Once authenticated, two server variables will be created with the keys PHP_AUTH_USER and PHP_AUTH_PW, which can be verified with the output of phpinfo() function.

    PHP HTTP Authentication 2

  • System Calls

    PHP’s library of built-in function includes a category of functions that deal with invoking operating system utilities and external programs from within the PHP code. In this chapter, we shall discuss the PHP functions used to perform system calls.

    The system() Function

    The system() function is similar to the system() function in C that it executes the given command and outputs the result.

    system(string$command,int&$result_code=null):string|false

    The system() call tries to automatically flush the web server’s output buffer after each line of output if PHP is running as a server module. It returns the last line of the command output on success, and false on failure.

    Example

    The following PHP snippet invokes DIR command of Windows OS and displays the list of files in the current directory.

    <?php
       echo '<pre>';
    
       // Outputs all the result of DOS command "dir", and returns
       // the last output line into $last_line. Stores the return value
       // of the shell command in $retval.
       $last_line = system('dir/w', $retval);
    
       // Printing additional info
       echo '
       </pre>
       <hr />Last line of the output: ' . $last_line . '
       <hr />Return value: ' . $retval;
    ?>

    It will produce the following output −

    Volume in drive C has no label.
    Volume Serial Number is 7EE4-E492
    
    Directory of C:\xampp\htdocs
    [.]                 [..]                applications.html   bitnami.css
    [dashboard]         employee.csv        favicon.ico         hello.csv
    hello.html          hello.php           homepage.php        [img]
    index.php           [Langi]             menu.php            myform.php
    myname.php          new.png             new.txt             test.php
    test.zip            [TPcodes]           uploadfile.php      [webalizer]
    welcome.png         [xampp]             
    
                 18 File(s)          123,694 bytes
                 8 Dir(s)            168,514,232,320 bytes free
    Last line of the output: 8 Dir(s) 168,514,232,320 bytes free Return value: 0

    The shell_exec() Function

    The shell_exec() function is identical to PHPs backtick operator. It executes the given command via shell and return the complete output as a string

    shell_exec(string$command):string|false|null

    The function returns a string containing the output from the executed command, false if the pipe cannot be established or null if an error occurs or the command produces no output.

    Example

    In the following code, we use shell_exec() function to obtain a list of files with “.php” as the extension in the current directory −

    <?php
       $output = shell_exec('dir *.php');
       echo "<pre>$output</pre>";
    ?>

    It will produce the following output −

    Volume in drive C has no label.
    Volume Serial Number is 7EE4-E492
    
    Directory of C:\xampp\htdocs
    
    10/26/2023  08:27 PM                73 hello.php
    10/12/2023  10:40 AM                61 homepage.php
    07/16/2015  09:02 PM               260 index.php
    10/12/2023  10:39 AM                49 menu.php
    09/25/2023  01:43 PM               338 myform.php
    10/12/2023  10:49 AM                51 myname.php
    10/26/2023  02:00 PM               369 test.php
    09/25/2023  01:42 PM               555 uploadfile.php
    
               8 File(s)          1,756 bytes
               0 Dir(s)           168,517,771,264 bytes free

    The exec() Function

    The exec() function executes the given command as a string argument.

    exec(string$command,array&$output=null,int&$result_code=null):string|false

    The $output parameter, if specified, is an array that will be filled with every line of output from the command.

    Example

    In this case, we use exec() function to call whoami command from inside the program. The whoami command returns the username.

    <?php
    
       // outputs the username that owns the running php/httpd process
       // (on a system with the "whoami" executable in the path)
       $output=null;
       $retval=null;
       exec('whoami', $output, $retval);
       echo "Returned with status $retval and output:\n";
       var_dump($output);
       
    ?>

    It will produce the following output −

    Returned with status 0 and output: array(1) 
    { [0]=> string(13) "gnvbgl3\mlath" }
    

    The passthru() Function

    The passthru() function executes an external program and display raw output. Though the passthru() function is similar to the exec() or system() function in that it executes a command, it should be used in their place when the output from the OS command is binary data which needs to be passed directly back to the browser.

    Example

    A PHP program that uses passthu() function to display the contents of system PATH environment variable

    passthru(string $command, int &$result_code = null): ?false
    <?php
       passthru ('PATH');
    ?>

    It will produce the following output −

    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\mlath\AppData\Local
    \Microsoft\WindowsApps;C:\VSCode\Microsoft VS Code\bin
    

    Backtick Operator

    PHP supports one execution operator: backticks (“). (they are not single-quotes!) PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned. Use of the backtick operator is identical to shell_exec().

    Example

    Take a look at the following example −

    <?php
       $output = dir *.php;
       echo "<pre>$output</pre>";
    ?>

    It will produce the following output −

    Volume in drive C has no label.
    Volume Serial Number is 7EE4-E492
    
    Directory of C:\xampp\htdocs
    
    10/26/2023  08:42 PM                61 hello.php
    10/12/2023  10:40 AM                61 homepage.php
    07/16/2015  09:02 PM               260 index.php
    10/12/2023  10:39 AM                49 menu.php
    09/25/2023  01:43 PM               338 myform.php
    10/12/2023  10:49 AM                51 myname.php
    10/26/2023  02:00 PM               369 test.php
    09/25/2023  01:42 PM               555 uploadfile.php
    
               8 File(s)          1,744 bytes
               0 Dir(s)           168,471,289,856 bytes free

    The backtick operator is disabled when shell_exec() is disabled.

  • Variable Handling is null Function

    The PHP Variable Handling is_null() function is used to checks whether a variable is null. It returns true when the variable is null. It returns false if the variable contains any value. This function is useful for determining if a variable is empty.

    It helps prevent errors caused by missing values. It can run PHP 4, PHP 5, PHP 7, and PHP 8. It can be used to validate user input, database values, and other information. It is a simple and easy to use PHP function.

    Syntax

    Below is the syntax of the PHP Variable Handling is_null() function −

    boolis_null(mixed$value)

    Parameters

    This function accepts $value parameter which is the variable that you want to check.

    Return Value

    The is_null() function returns TRUE if the variable is null. And it returns FALSE if the variable has a value.

    PHP Version

    First introduced in core PHP 4.0.4, the is_null() function continues to function easily in PHP 5, PHP 7, and PHP 8.

    Example 1

    This program uses the PHP Variable Handling is_null() function to check whether a variable is null. If the variable is null, it will say “Variable is null”. Otherwise, it states “Variable is not null”. This is a simple example showing how is_null() works.

    <?php
       // Assigning null value
       $var = null; 
       if (is_null($var)) {
    
      echo "Variable is null"; 
    } else {
      echo "Variable is not null";
    } ?>

    Output

    Here is the outcome of the following code −

    Variable is null
    

    Example 2

    This program checks if an undefined variable is null. As the variable has not been declared, is_null() function returns true. This helps to prevent errors caused by missing variables. It provides the safe execution of PHP code.

    <?php
       if (is_null($undefinedVar)) {
    
      echo "Variable is null"; 
    } else {
      echo "Variable is not null";
    } ?>

    Output

    This will generate the below output −

    Variable is null
    

    Example 3

    This program checks if an array element is null using the is_null() function. It is useful for working with user input and database records. If the element is null, it will say “Element is null”. Otherwise, it will show “Element is not null”.

    <?php
       // Associative array with a null value
       $data = ["name" => "John", "age" => null]; 
       if (is_null($data["age"])) {
    
      echo "Element is null"; 
    } else {
      echo "Element is not null";
    } ?>

    Output

    This will create the below output −

    Element is null