Blog

  • PHP Parsing Directories

    Working with Directories in PHP

    In the previous chapter you’ve learned how to work with files in PHP. Similarly, PHP also allows you to work with directories on the file system, for example, you can open a directory and read its contents, create or delete a directory, list all files in the directory, and so on.

    Creating a New Directory

    You can create a new and empty directory by calling the PHP mkdir() function with the path and name of the directory to be created, as shown in the example below:

    Example

    <?php
    // The directory path
    $dir = "testdir";
     
    // Check the existence of directory
    if(!file_exists($dir)){
        // Attempt to create directory
        if(mkdir($dir)){
            echo "Directory created successfully.";
        } else{
            echo "ERROR: Directory could not be created.";
        }
    } else{
        echo "ERROR: Directory already exists.";
    }
    ?>

    To make the mkdir() function work, the parent directories in the directory path parameter has to exist already, for example, if you specify the directory path as testdir/subdir than the testdir has to exist otherwise PHP will generate an error.


    Copying Files from One Location to Another

    You can copy a file from one location to another by calling PHP copy() function with the file’s source and destination paths as arguments. If the destination file already exists it’ll be overwritten. Here’s an example which creates a copy of “example.txt” file inside backup folder.

    Example

    <?php
    // Source file path
    $file = "example.txt";
     
    // Destination file path
    $newfile = "backup/example.txt";
     
    // Check the existence of file
    if(file_exists($file)){
        // Attempt to copy file
        if(copy($file, $newfile)){
            echo "File copied successfully.";
        } else{
            echo "ERROR: File could not be copied.";
        }
    } else{
        echo "ERROR: File does not exist.";
    }
    ?>

    To make this example work, the target directory which is backup and the source file i.e. “example.txt” has to exist already; otherwise PHP will generate an error.


    Listing All Files in a Directory

    You can use the PHP scandir() function to list files and directories inside the specified path.

    Now we’re going to create a custom function that will recursively list all files in a directory using PHP. This script will be helpful if you’re working with deeply nested directory structure.

    Example

    <?php
    // Define a function to output files in a directory
    function outputFiles($path){
        // Check directory exists or not
        if(file_exists($path) && is_dir($path)){
            // Scan the files in this directory
            $result = scandir($path);
            
            // Filter out the current (.) and parent (..) directories
            $files = array_diff($result, array('.', '..'));
            
            if(count($files) > 0){
                // Loop through retuned array
                foreach($files as $file){
                    if(is_file("$path/$file")){
                        // Display filename
                        echo $file . "<br>";
                    } else if(is_dir("$path/$file")){
                        // Recursively call the function if directories found
                        outputFiles("$path/$file");
                    }
                }
            } else{
                echo "ERROR: No files found in the directory.";
            }
        } else {
            echo "ERROR: The directory does not exist.";
        }
    }
     
    // Call the function
    outputFiles("mydir");
    ?>

    Listing All Files of a Certain Type

    While working on directory and file structure, sometimes you might need to find out certain types of files within the directory, for example, listing only .text or .png files, etc. You can do this easily with the PHP glob() function, which matches files based on the pattern.

    The PHP code in the following example will search the documents directory and list all the files with .text extension. It will not search the subdirectories.

    Example

    <?php
    /* Search the directory and loop through
    returned array containing the matched files */
    foreach(glob("documents/*.txt") as $file){
        echo basename($file) . " (size: " . filesize($file) . " bytes)" . "<br>";
    }
    ?>

    The glob() function can also be used to find all the files within a directory or its subdirectories. The function defined in the following example will recursively list all files within a directory, just like we’ve done in previous example with the scandir() function.

    Example

    <?php
    // Define a function to output files in a directory
    function outputFiles($path){
        // Check directory exists or not
        if(file_exists($path) && is_dir($path)){
            // Search the files in this directory
            $files = glob($path ."/*");
            if(count($files) > 0){
                // Loop through retuned array
                foreach($files as $file){
                    if(is_file("$file")){
                        // Display only filename
                        echo basename($file) . "<br>";
                    } else if(is_dir("$file")){
                        // Recursively call the function if directories found
                        outputFiles("$file");
                    }
                }
            } else{
                echo "ERROR: No such file found in the directory.";
            }
        } else {
            echo "ERROR: The directory does not exist.";
        }
    }
     
    // Call the function
    outputFiles("mydir");
    ?>
  • PHP File System

    Working with Files in PHP

    Since PHP is a server side programming language, it allows you to work with files and directories stored on the web server. In this tutorial you will learn how to create, access, and manipulate files on your web server using the PHP file system functions.

    Opening a File with PHP fopen() Function

    To work with a file you first need to open the file. The PHP fopen() function is used to open a file. The basic syntax of this function can be given with:

    fopen(filenamemode)

    The first parameter passed to fopen() specifies the name of the file you want to open, and the second parameter specifies in which mode the file should be opened. For example:

    Example

    <?php
    $handle = fopen("data.txt", "r");
    ?>

    The file may be opened in one of the following modes:

    ModesWhat it does
    rOpen the file for reading only.
    r+Open the file for reading and writing.
    wOpen the file for writing only and clears the contents of file. If the file does not exist, PHP will attempt to create it.
    w+Open the file for reading and writing and clears the contents of file. If the file does not exist, PHP will attempt to create it.
    aAppend. Opens the file for writing only. Preserves file content by writing to the end of the file. If the file does not exist, PHP will attempt to create it.
    a+Read/Append. Opens the file for reading and writing. Preserves file content by writing to the end of the file. If the file does not exist, PHP will attempt to create it.
    xOpen the file for writing only. Return FALSE and generates an error if the file already exists. If the file does not exist, PHP will attempt to create it.
    x+Open the file for reading and writing; otherwise it has the same behavior as ‘x’.

    If you try to open a file that doesn’t exist, PHP will generate a warning message. So, to avoid these error messages you should always implement a simple check whether a file or directory exists or not before trying to access it, with the PHP file_exists() function.

    Example

    <?php
    $file = "data.txt";
     
    // Check the existence of file
    if(file_exists($file)){
        // Attempt to open the file
        $handle = fopen($file, "r");
    } else{
        echo "ERROR: File does not exist.";
    }
    ?>

    Tip: Operations on files and directories are prone to errors. So it’s a good practice to implement some form of error checking so that if an error occurs your script will handle the error gracefully. See the tutorial on PHP error handling.


    Closing a File with PHP fclose() Function

    Once you’ve finished working with a file, it needs to be closed. The fclose() function is used to close the file, as shown in the following example:

    Example

    <?php
    $file = "data.txt";
     
    // Check the existence of file
    if(file_exists($file)){
        // Open the file for reading
        $handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
            
        /* Some code to be executed */
            
        // Closing the file handle
        fclose($handle);
    } else{
        echo "ERROR: File does not exist.";
    }
    ?>

    Note: Although PHP automatically closes all open files when script terminates, but it’s a good practice to close a file after performing all the operations.


    Reading from Files with PHP fread() Function

    Now that you have understood how to open and close files. In the following section you will learn how to read data from a file. PHP has several functions for reading data from a file. You can read from just one character to the entire file with a single operation.

    Reading Fixed Number of Characters

    The fread() function can be used to read a specified number of characters from a file. The basic syntax of this function can be given with.

    fread(file handlelength in bytes)

    This function takes two parameter — A file handle and the number of bytes to read. The following example reads 20 bytes from the “data.txt” file including spaces. Let’s suppose the file “data.txt” contains a paragraph of text “The quick brown fox jumps over the lazy dog.”

    Example

    <?php
    $file = "data.txt";
     
    // Check the existence of file
    if(file_exists($file)){
        // Open the file for reading
        $handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
            
        // Read fixed number of bytes from the file
        $content = fread($handle, "20");
            
        // Closing the file handle
        fclose($handle);
            
        // Display the file content 
        echo $content;
    } else{
        echo "ERROR: File does not exist.";
    }
    ?>

    The above example will produce the following output:

    The quick brown fox

    Reading the Entire Contents of a File

    The fread() function can be used in conjugation with the filesize() function to read the entire file at once. The filesize() function returns the size of the file in bytes.

    Example

    <?php
    $file = "data.txt";
     
    // Check the existence of file
    if(file_exists($file)){
        // Open the file for reading
        $handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
            
        // Reading the entire file
        $content = fread($handle, filesize($file));
            
        // Closing the file handle
        fclose($handle);
            
        // Display the file content
        echo $content;
    } else{
        echo "ERROR: File does not exist.";
    }
    ?>

    The above example will produce the following output:

    The quick brown fox jumps over the lazy dog.

    The easiest way to read the entire contents of a file in PHP is with the readfile() function. This function allows you to read the contents of a file without needing to open it. The following example will generate the same output as above example:

    Example

    <?php
    $file = "data.txt";
     
    // Check the existence of file
    if(file_exists($file)){
        // Reads and outputs the entire file
        readfile($file) or die("ERROR: Cannot open the file.");
    } else{
        echo "ERROR: File does not exist.";
    }
    ?>

    The above example will produce the following output:

    The quick brown fox jumps over the lazy dog.

    Another way to read the whole contents of a file without needing to open it is with the file_get_contents() function. This function accepts the name and path to a file, and reads the entire file into a string variable. Here’s an example:

    Example

    <?php
    $file = "data.txt";
     
    // Check the existence of file
    if(file_exists($file)){
        // Reading the entire file into a string
        $content = file_get_contents($file) or die("ERROR: Cannot open the file.");
            
        // Display the file content 
        echo $content;
    } else{
        echo "ERROR: File does not exist.";
    }
    ?>

    One more method of reading the whole data from a file is the PHP’s file() function. It does a similar job to file_get_contents() function, but it returns the file contents as an array of lines, rather than a single string. Each element of the returned array corresponds to a line in the file.

    To process the file data, you need to iterate over the array using a foreach loop. Here’s an example, which reads a file into an array and then displays it using the loop:

    Example

    <?php
    $file = "data.txt";
     
    // Check the existence of file
    if(file_exists($file)){
        // Reading the entire file into an array
        $arr = file($file) or die("ERROR: Cannot open the file.");
        foreach($arr as $line){
            echo $line;
        }
    } else{
        echo "ERROR: File does not exist.";
    }
    ?>

    Writing the Files Using PHP fwrite() Function

    Similarly, you can write data to a file or append to an existing file using the PHP fwrite() function. The basic syntax of this function can be given with:

    fwrite(file handlestring)

    The fwrite() function takes two parameter — A file handle and the string of data that is to be written, as demonstrated in the following example:

    Example

    <?php
    $file = "note.txt";
        
    // String of data to be written
    $data = "The quick brown fox jumps over the lazy dog.";
        
    // Open the file for writing
    $handle = fopen($file, "w") or die("ERROR: Cannot open the file.");
        
    // Write data to the file
    fwrite($handle, $data) or die ("ERROR: Cannot write the file.");
        
    // Closing the file handle
    fclose($handle);
        
    echo "Data written to the file successfully.";
    ?>

    In the above example, if the “note.txt” file doesn’t exist PHP will automatically create it and write the data. But, if the “note.txt” file already exist, PHP will erase the contents of this file, if it has any, before writing the new data, however if you just want to append the file and preserve existing contents just use the mode a instead of w in the above example.

    An alternative way is using the file_put_contents() function. It is counterpart of file_get_contents() function and provides an easy method of writing the data to a file without needing to open it. This function accepts the name and path to a file together with the data to be written to the file. Here’s an example:

    Example

    <?php
    $file = "note.txt";
        
    // String of data to be written
    $data = "The quick brown fox jumps over the lazy dog.";
        
    // Write data to the file
    file_put_contents($file, $data) or die("ERROR: Cannot write the file.");
        
    echo "Data written to the file successfully.";
    ?>

    If the file specified in the file_put_contents() function already exists, PHP will overwrite it by default. If you would like to preserve the file’s contents you can pass the special FILE_APPEND flag as a third parameter to the file_put_contents() function. It will simply append the new data to the file instead of overwitting it. Here’s an example:

    Example

    <?php
    $file = "note.txt";
        
    // String of data to be written
    $data = "The quick brown fox jumps over the lazy dog.";
        
    // Write data to the file
    file_put_contents($file, $data, FILE_APPEND) or die("ERROR: Cannot write the file.");
        
    echo "Data written to the file successfully.";
    ?>

    Renaming Files with PHP rename() Function

    You can rename a file or directory using the PHP’s rename() function, like this:

    Example

    <?php
    $file = "file.txt";
     
    // Check the existence of file
    if(file_exists($file)){
        // Attempt to rename the file
        if(rename($file, "newfile.txt")){
            echo "File renamed successfully.";
        } else{
            echo "ERROR: File cannot be renamed.";
        }
    } else{
        echo "ERROR: File does not exist.";
    }
    ?>

    Removing Files with PHP unlink() Function

    You can delete files or directories using the PHP’s unlink() function, like this:

    Example

    <?php
    $file = "note.txt";
     
    // Check the existence of file
    if(file_exists($file)){
        // Attempt to delete the file
        if(unlink($file)){
            echo "File removed successfully.";
        } else{
            echo "ERROR: File cannot be removed.";
        }
    } else{
        echo "ERROR: File does not exist.";
    }
    ?>

    In the next chapter we will learn more about parsing directories or folders in PHP.


    PHP Filesystem Functions

    The following table provides the overview of some other useful PHP filesystem functions that can be used for reading and writing the files dynamically.

    FunctionDescription
    fgetc()Reads a single character at a time.
    fgets()Reads a single line at a time.
    fgetcsv()Reads a line of comma-separated values.
    filetype()Returns the type of the file.
    feof()Checks whether the end of the file has been reached.
    is_file()Checks whether the file is a regular file.
    is_dir()Checks whether the file is a directory.
    is_executable()Checks whether the file is executable.
    realpath()Returns canonicalized absolute pathname.
    rmdir()Removes an empty directory.

    Please check out the PHP filesystem reference for other useful PHP filesystem functions.

  • PHP Include and Require Files

    Including a PHP File into Another PHP File

    The include() and require() statement allow you to include the code contained in a PHP file within another PHP file. Including a file produces the same result as copying the script from the file specified and pasted into the location where it is called.

    You can save a lot of time and work through including files — Just store a block of code in a separate file and include it wherever you want using the include() and require() statements instead of typing the entire block of code multiple times. A typical example is including the header, footer and menu file within all the pages of a website.

    The basic syntax of the include() and require() statement can be given with:

    include("path/to/filename"); -Or- include "path/to/filename";
    require("path/to/filename"); -Or- require "path/to/filename";

    Tip: Like the print and echo statements, you can omit the parentheses while using the include and require statements as demonstrated above.

    The following example will show you how to include the common header, footer and menu codes which are stored in separate ‘header.php’, ‘footer.php’ and ‘menu.php’ files respectively, within all the pages of your website. Using this technique you can update all pages of the website at once by making the changes to just one file, this saves a lot of repetitive work.

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Tutorial Republic</title>
    </head>
    <body>
    <?php include "header.php"; ?>
    <?php include "menu.php"; ?>
        <h1>Welcome to Our Website!</h1>
        <p>Here you will find lots of useful information.</p>
    <?php include "footer.php"; ?>
    </body>
    </html>

    Difference Between include and require Statements

    You might be thinking if we can include files using the include() statement then why we need require(). Typically the require() statement operates like include().

    The only difference is — the include() statement will only generate a PHP warning but allow script execution to continue if the file to be included can’t be found, whereas the require() statement will generate a fatal error and stops the script execution.

    Example

    <?php require "my_variables.php"; ?>
    <?php require "my_functions.php"; ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title><?php displayTitle($home_page); ?></title>
    </head>
    <body>
    <?php include "header.php"; ?>
    <?php include "menu.php"; ?>
        <h1>Welcome to Our Website!</h1>
        <p>Here you will find lots of useful information.</p>
    <?php include "footer.php"; ?>
    </body>
    </html>

    Tip: It is recommended to use the require() statement if you’re including the library files or files containing the functions and configuration variables that are essential for running your application, such as database configuration file.


    The include_once and require_once Statements

    If you accidentally include the same file (typically functions or classes files) more than one time within your code using the include or require statements, it may cause conflicts. To prevent this situation, PHP provides include_once and require_once statements. These statements behave in the same way as include and require statements with one exception.

    The include_once and require_once statements will only include the file once even if asked to include it a second time i.e. if the specified file has already been included in a previous statement, the file is not included again. To better understand how it works, let’s check out an example. Suppose we’ve a ‘my_functions.php’ file with the following code:

    Example

    <?php
    function multiplySelf($var){
        $var *= $var; // multiply variable by itself
        echo $var;
    }
    ?>

    Here’s is the PHP script within which we’ve included the ‘my_functions.php’ file.

    Example

    <?php
    // Including file
    require "my_functions.php";
    // Calling the function
    multiplySelf(2); // Output: 4
    echo "<br>";
     
    // Including file once again
    require "my_functions.php";
    // Calling the function
    multiplySelf(5); // Doesn't execute
    ?>

    When you run the above script, you will see the error message something like this: “Fatal error: Cannot redeclare multiplySelf()”. This occurs because the ‘my_functions.php’ included twice, this means the function multiplySelf() is defined twice, which caused PHP to stop script execution and generate fatal error. Now rewrite the above example with require_once.

    Example

    <?php
    // Including file
    require_once "my_functions.php";
    // Calling the function
    multiplySelf(2); // Output: 4
    echo "<br>";
     
    // Including file once again
    require_once "my_functions.php";
    // Calling the function
    multiplySelf(5); // Output: 25
    ?>

    As you can see, by using require_once instead of require, the script works as we expected.

  • PHP Date and Time

    The PHP Date() Function

    The PHP date() function convert a timestamp to a more readable date and time.

    The computer stores dates and times in a format called UNIX Timestamp, which measures time as a number of seconds since the beginning of the Unix epoch (midnight Greenwich Mean Time on January 1, 1970 i.e. January 1, 1970 00:00:00 GMT ).

    Since this is an impractical format for humans to read, PHP converts a timestamp to a format that is readable to humans and dates from your notation into a timestamp the computer understands. The syntax of the PHP date() function can be given with.

    date(formattimestamp)

    The format parameter in the date() function is required which specifies the format of returned date and time. However the timestamp is an optional parameter, if not included then current date and time will be used. The following statement displays today’s date:

    Example

    <?php
    $today = date("d/m/Y");
    echo $today;
    ?>

    Note: The PHP date() function return the current date and time according to the built-in clock of the web server on which the script has been executed.


    Formatting the Dates and Times with PHP

    The format parameter of the date() function is in fact a string that can contain multiple characters allowing you to generate a date string containing various components of the date and time, like day of the week, AM or PM, etc. Here are some the date-related formatting characters that are commonly used in format string:

    • d – Represent day of the month; two digits with leading zeros (01 or 31)
    • D – Represent day of the week in text as an abbreviation (Mon to Sun)
    • m – Represent month in numbers with leading zeros (01 or 12)
    • M – Represent month in text, abbreviated (Jan to Dec)
    • y – Represent year in two digits (08 or 14)
    • Y – Represent year in four digits (2008 or 2014)

    The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.), slashes (/), or spaces to add additional visual formatting.

    Example

    <?php
    echo date("d/m/Y") . "<br>";
    echo date("d-m-Y") . "<br>";
    echo date("d.m.Y");
    ?>

    Tip: You can use the PHP date() function to automatically update the copyright duration on your website, like: Copyright &copy; 2010-<?php echo date("Y")?>.

    Similarly you can use the following characters to format the time string:

    • h – Represent hour in 12-hour format with leading zeros (01 to 12)
    • H – Represent hour in in 24-hour format with leading zeros (00 to 23)
    • i – Represent minutes with leading zeros (00 to 59)
    • s – Represent seconds with leading zeros (00 to 59)
    • a – Represent lowercase ante meridiem and post meridiem (am or pm)
    • A – Represent uppercase Ante meridiem and Post meridiem (AM or PM)

    The PHP code in the following example displays the date in different formats:

    Example

    <?php
    echo date("h:i:s") . "<br>";
    echo date("F d, Y h:i:s A") . "<br>";
    echo date("h:i a");
    ?>

    The PHP time() Function

    The time() function is used to get the current time as a Unix timestamp (the number of seconds since the beginning of the Unix epoch: January 1 1970 00:00:00 GMT).

    Example

    <?php
    // Executed at March 05, 2014 07:19:18
    $timestamp = time();
    echo($timestamp);
    ?>

    The above example produce the following output.

    1394003958

    We can convert this timestamp to a human readable date through passing it to the previously introduce date() function.

    Example

    <?php
    $timestamp = 1394003958;
    echo(date("F d, Y h:i:s", $timestamp));
    ?>

    The above example produce the following output.

    March 05, 2014 07:19:18


    The PHP mktime() Function

    The mktime() function is used to create the timestamp based on a specific date and time. If no date and time is provided, the timestamp for the current date and time is returned.

    The syntax of the mktime() function can be given with:

    mktime(hourminutesecondmonthdayyear)

    The following example displays the timestamp corresponding to 3:20:12 pm on May 10, 2014:

    Example

    <?php
    // Create the timestamp for a particular date
    echo mktime(15, 20, 12, 5, 10, 2014);
    ?>

    The above example produce the following output.

    1399735212

    Note: You can leave out as many arguments as you like, and the value corresponding to the current time will be used instead. If you omit all the arguments, the mktime() function will return the UNIX timestamp corresponding to the current date and time, just like time().

    The mktime() function can be used to find the weekday name corresponding to a particular date. To do this, simply use the ‘l’ (lowercase ‘L’) character with your timestamp, as in the following example, which displays the day that falls on April 1, 2014:

    Example

    <?php
    // Get the weekday name of a particular date
    echo date('l', mktime(0, 0, 0, 4, 1, 2014));
    ?>

    The above example produce the following output.

    Tuesday

    The mktime() function can also be used to find a particular date in future after a specific time period. As in the following example, which displays the date which falls on after 30 month from the current date?

    Example

    <?php
    // Executed at March 05, 2014
    $futureDate = mktime(0, 0, 0, date("m")+30, date("d"), date("Y"));
    echo date("d/m/Y", $futureDate);
    ?>

    The above example produce the following output.

    05/09/2016


    Complete PHP Date Reference

    Please check out the PHP Date/Time Functions reference section for a complete list of all the useful date and time functions available in PHP.

  • PHP GET and POST

    Methods of Sending Information to Server

    A web browser communicates with the server typically using one of the two HTTP (Hypertext Transfer Protocol) methods — GET and POST. Both methods pass the information differently and have different advantages and disadvantages, as described below.

    The GET Method

    In GET method the data is sent as URL parameters that are usually strings of name and value pairs separated by ampersands (&). In general, a URL with GET data will look like this:

    http://www.example.com/action.php?name=john&age=24

    The bold parts in the URL are the GET parameters and the italic parts are the value of those parameters. More than one parameter=value can be embedded in the URL by concatenating with ampersands (&). One can only send simple text data via GET method.

    Advantages and Disadvantages of Using the GET Method

    • Since the data sent by the GET method are displayed in the URL, it is possible to bookmark the page with specific query string values.
    • The GET method is not suitable for passing sensitive information such as the username and password, because these are fully visible in the URL query string as well as potentially stored in the client browser’s memory as a visited page.
    • Because the GET method assigns data to a server environment variable, the length of the URL is limited. So, there is a limitation for the total data to be sent.

    PHP provides the superglobal variable $_GET to access all the information sent either through the URL or submitted through an HTML form using the method="get".

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Example of PHP GET method</title>
    </head>
    <body>
    <?php
    if(isset($_GET["name"])){
        echo "<p>Hi, " . $_GET["name"] . "</p>";
    }
    ?>
    <form method="get" action="<?php echo $_SERVER["PHP_SELF"];?>">
        <label for="inputName">Name:</label>
        <input type="text" name="name" id="inputName">
        <input type="submit" value="Submit">
    </form>
    </body>

    The POST Method

    In POST method the data is sent to the server as a package in a separate communication with the processing script. Data sent through POST method will not visible in the URL.

    Advantages and Disadvantages of Using the POST Method

    • It is more secure than GET because user-entered information is never visible in the URL query string or in the server logs.
    • There is a much larger limit on the amount of data that can be passed and one can send text data as well as binary data (uploading a file) using POST.
    • Since the data sent by the POST method is not visible in the URL, so it is not possible to bookmark the page with specific query.

    Like $_GET, PHP provide another superglobal variable $_POST to access all the information sent via post method or submitted through an HTML form using the method="post".

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Example of PHP POST method</title>
    </head>
    <body>
    <?php
    if(isset($_POST["name"])){
        echo "<p>Hi, " . $_POST["name"] . "</p>";
    }
    ?>
    <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
        <label for="inputName">Name:</label>
        <input type="text" name="name" id="inputName">
        <input type="submit" value="Submit">
    </form>
    </body>

    The $_REQUEST Variable

    PHP provides another superglobal variable $_REQUEST that contains the values of both the $_GET and $_POST variables as well as the values of the $_COOKIE superglobal variable.

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Example of PHP $_REQUEST variable</title>
    </head>
    <body>
    <?php
    if(isset($_REQUEST["name"])){
        echo "<p>Hi, " . $_REQUEST["name"] . "</p>";
    }
    ?>
    <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
        <label for="inputName">Name:</label>
        <input type="text" name="name" id="inputName">
        <input type="submit" value="Submit">
    </form>
    </body>

    You will learn more about PHP cookies and form handling in advanced section.

  • PHP Math Operations

    Performing Math Operations

    PHP has several built-in functions that help you perform anything from simple additions or subtraction to advanced calculations. You’ve already seen how to perform basic mathematical operations in PHP operators chapter. Let’s check out one more example:

    Example

    <?php
    echo 7 + 3; // 0utputs: 10
    echo 7 - 2; // 0utputs: 5
    echo 7 * 2; // 0utputs: 14
    echo 7 / 2; // 0utputs: 3.5
    echo 7 % 2; // 0utputs: 1
    ?>

    Every math operation has a certain precedence level; generally multiplication and division are performed before addition and subtraction. However, parentheses can alter this precedence; expressions enclosed within parentheses are always evaluated first, regardless of the operation’s precedence level, as demonstrated in the following example:

    Example

    <?php
    echo 5 + 4 * 10;         // 0utputs: 45
    echo (5 + 4) * 10;       // 0utputs: 90
    echo 5 + 4 * 10 / 2;     // 0utputs: 25
    echo 8 * 10 / 4 - 2;     // 0utputs: 18
    echo 8 * 10 / (4 - 2);   // 0utputs: 40
    echo 8 + 10 / 4 - 2;     // 0utputs: 8.5
    echo (8 + 10) / (4 - 2); // 0utputs: 9
    ?>

    In the following section we’re going to look at some built-in PHP functions that are most frequently used in performing mathematical operations.


    Find the Absolute Value of a Number

    The absolute value of an integer or a float can be found with the abs() function, as demonstrated in the following example:

    Example

    <?php
    echo abs(5);    // 0utputs: 5 (integer)
    echo abs(-5);   // 0utputs: 5 (integer)
    echo abs(4.2);  // 0utputs: 4.2 (double/float)
    echo abs(-4.2); // 0utputs: 4.2 (double/float)
    ?>

    As you can see if the given number is negative, the valued returned is positive. But, if the number is positive, this function simply returns the number.


    Round a Fractional Value Up or Down

    The ceil() function can be used to round a fractional value up to the next highest integer value, whereas the floor() function can be used to round a fractional value down to the next lowest integer value, as demonstrated in the following example:

    Example

    <?php
    // Round fractions up
    echo ceil(4.2);    // 0utputs: 5
    echo ceil(9.99);   // 0utputs: 10
    echo ceil(-5.18);  // 0utputs: -5
     
    // Round fractions down
    echo floor(4.2);    // 0utputs: 4
    echo floor(9.99);   // 0utputs: 9
    echo floor(-5.18);  // 0utputs: -6
    ?>

    Find the Square Root of a Number

    You can use the sqrt() function to find the square root of a positive number. This function returns a special value NAN for negative numbers. Here’s an example:

    Example

    <?php
    echo sqrt(9);   // 0utputs: 3
    echo sqrt(25);  // 0utputs: 5
    echo sqrt(10);  // 0utputs: 3.1622776601684
    echo sqrt(-16); // 0utputs: NAN
    ?>

    Generate a Random Number

    The rand() function can be used to generate a random number. You can optionally specify a range by passing the min, max arguments, as shown in the following example:

    Example

    <?php
    // Generate some random numbers
    echo rand() . "<br>";
    echo rand() . "<br>";
     
    // Generate some random numbers between 1 and 10 (inclusive)
    echo rand(1, 10) . "<br>";
    echo rand(1, 10) . "<br>";
    ?>

    If rand() function is called without the optional minmax arguments, it returns a pseudo-random number between 0 and getrandmax(). The getrandmax() function show the largest possible random value, which is only 32767 on Windows platform. So, if you require a range larger than 32767, you may simply specify the min and max arguments.


    Convert Decimal Numbers to Binary and Vice Versa

    The decbin() function is used to convert a decimal number into binary number. Whereas its counterpart the bindec() function converts a number from binary to decimal.

    Example

    <?php
    // Convert Decimal to Binary 
    echo decbin(2);    // 0utputs: 10  
    echo decbin(12);   // 0utputs: 1100  
    echo decbin(100);  // 0utputs: 1100100
     
    // Convert Binary to Decimal
    echo bindec(10);       // 0utputs: 2 
    echo bindec(1100);     // 0utputs: 12  
    echo bindec(1100100);  // 0utputs: 100
    ?>

    Convert Decimal Numbers to Hexadecimal and Vice Versa

    The dechex() function is used to convert a decimal number into hexadecimal representation. Whereas, the hexdec() function is used to converts a hexadecimal string to a decimal number.

    Example

    <?php
    // Convert decimal to hexadecimal 
    echo dechex(255);  // 0utputs: ff
    echo dechex(196);  // 0utputs: c4
    echo dechex(0);    // 0utputs: 0
     
    // Convert hexadecimal to decimal
    echo hexdec('ff');  // 0utputs: 255
    echo hexdec('c4');  // 0utputs: 196
    echo hexdec(0);     // 0utputs: 0
    ?>

    Convert Decimal Numbers to Octal and Vice Versa

    The decoct() function is used to convert a decimal number into octal representation. Whereas, the octdec() function is used to converts a octal number to a decimal number.

    Example

    <?php
    // Convert decimal to octal 
    echo decoct(12);   // 0utputs: 14
    echo decoct(256);  // 0utputs: 400
    echo decoct(77);   // 0utputs: 115
     
    // Convert octal to decimal
    echo octdec('14');   // 0utputs: 12
    echo octdec('400');  // 0utputs: 256
    echo octdec('115');  // 0utputs: 77
    ?>

    Convert a Number from One Base System to Another

    The base_convert() function can be used to convert a number from one base system to other. For example, you can convert decimal (base 10) to binary (base 2), hexadecimal (base 16) to octal (base 8), octal to hexadecimal, hexadecimal to decimal, and so on.

    This function accepts three parameters: the number to convert, the base it’s currently in, and the base it’s to be converted to. The basic syntax is as follows:

    base_convert(number, frombase, tobase);

    Here, the number can be either an integer or a string representing an integer. Both frombase and tobase have to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, where a means 10, b means 11 and z means 35. Here’s a simple example to show how this function works:

    Example

    <?php
    // Convert decimal to binary
    echo base_convert('12', 10, 2);  // 0utputs: 1100
    // Convert binary to decimal
    echo base_convert('1100', 2, 10);  // 0utputs: 12
     
    // Convert decimal to hexadecimal
    echo base_convert('10889592', 10, 16);  // 0utputs: a62978
    // Convert hexadecimal to decimal
    echo base_convert('a62978', 16, 10);  // 0utputs: 10889592
     
    // Convert decimal to octal
    echo base_convert('82', 10, 8);  // 0utputs: 122
    // Convert octal to decimal
    echo base_convert('122', 8, 10);  // 0utputs: 82
     
    // Convert hexadecimal to octal
    echo base_convert('c2c6a8', 16, 8);  // 0utputs: 60543250
    // Convert octal to hexadecimal
    echo base_convert('60543250', 8, 16);  // 0utputs: c2c6a8
     
    // Convert octal to binary
    echo base_convert('42', 8, 2);  // 0utputs: 100010
    // Convert binary to octal
    echo base_convert('100010', 2, 8);  // 0utputs: 42
     
    // Convert hexadecimal to binary
    echo base_convert('abc', 16, 2);  // 0utputs: 101010111100
    // Convert binary to hexadecimal
    echo base_convert('101010111100', 2, 16);  // 0utputs: abc
    ?>
  • PHP Functions

    PHP Built-in Functions

    A function is a self-contained block of code that performs a specific task.

    PHP has a huge collection of internal or built-in functions that you can call directly within your PHP scripts to perform a specific task, like gettype()print_r()var_dump, etc.

    Please check out PHP reference section for a complete list of useful PHP built-in functions.

    PHP User-Defined Functions

    In addition to the built-in functions, PHP also allows you to define your own functions. It is a way to create reusable code packages that perform specific tasks and can be kept and maintained separately form main program. Here are some advantages of using functions:

    • Functions reduces the repetition of code within a program — Function allows you to extract commonly used block of code into a single component. Now you can perform the same task by calling this function wherever you want within your script without having to copy and paste the same block of code again and again.
    • Functions makes the code much easier to maintain — Since a function created once can be used many times, so any changes made inside a function automatically implemented at all the places without touching the several files.
    • Functions makes it easier to eliminate the errors — When the program is subdivided into functions, if any error occur you know exactly what function causing the error and where to find it. Therefore, fixing errors becomes much easier.
    • Functions can be reused in other application — Because a function is separated from the rest of the script, it’s easy to reuse the same function in other applications just by including the php file containing those functions.

    The following section will show you how easily you can define your own function in PHP.


    Creating and Invoking Functions

    The basic syntax of creating a custom function can be give with:

    function functionName(){
    // Code to be executed
    }

    The declaration of a user-defined function start with the word function, followed by the name of the function you want to create followed by parentheses i.e. () and finally place your function’s code between curly brackets {}.

    This is a simple example of an user-defined function, that display today’s date:

    Example

    <?php
    // Defining function
    function whatIsToday(){
        echo "Today is " . date('l', mktime());
    }
    // Calling function
    whatIsToday();
    ?>

    Note: A function name must start with a letter or underscore character not with a number, optionally followed by the more letters, numbers, or underscore characters. Function names are case-insensitive.


    Functions with Parameters

    You can specify parameters when you define your function to accept input values at run time. The parameters work like placeholder variables within a function; they’re replaced at run time by the values (known as argument) provided to the function at the time of invocation.

    function myFunc($oneParameter, $anotherParameter){
    // Code to be executed
    }

    You can define as many parameters as you like. However for each parameter you specify, a corresponding argument needs to be passed to the function when it is called.

    The getSum() function in following example takes two integer values as arguments, simply add them together and then display the result in the browser.

    Example

    <?php
    // Defining function
    function getSum($num1, $num2){
      $sum = $num1 + $num2;
      echo "Sum of the two numbers $num1 and $num2 is : $sum";
    }
     
    // Calling function
    getSum(10, 20);
    ?>

    The output of the above code will be:

    Sum of the two numbers 10 and 20 is : 30

    Tip: An argument is a value that you pass to a function, and a parameter is the variable within the function that receives the argument. However, in common usage these terms are interchangeable i.e. an argument is a parameter is an argument.


    Functions with Optional Parameters and Default Values

    You can also create functions with optional parameters — just insert the parameter name, followed by an equals (=) sign, followed by a default value, like this.

    Example

    <?php
    // Defining function
    function customFont($font, $size=1.5){
        echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello, world!</p>";
    }
     
    // Calling function
    customFont("Arial", 2);
    customFont("Times", 3);
    customFont("Courier");
    ?>

    As you can see the third call to customFont() doesn’t include the second argument. This causes PHP engine to use the default value for the $size parameter which is 1.5.


    Returning Values from a Function

    A function can return a value back to the script that called the function using the return statement. The value may be of any type, including arrays and objects.

    Example

    <?php
    // Defining function
    function getSum($num1, $num2){
        $total = $num1 + $num2;
        return $total;
    }
     
    // Printing returned value
    echo getSum(5, 10); // Outputs: 15
    ?>

    A function can not return multiple values. However, you can obtain similar results by returning an array, as demonstrated in the following example.

    Example

    <?php
    // Defining function
    function divideNumbers($dividend, $divisor){
        $quotient = $dividend / $divisor;
        $array = array($dividend, $divisor, $quotient);
        return $array;
    }
     
    // Assign variables as if they were an array
    list($dividend, $divisor, $quotient) = divideNumbers(10, 2);
    echo $dividend;  // Outputs: 10
    echo $divisor;   // Outputs: 2
    echo $quotient;  // Outputs: 5
    ?>

    Passing Arguments to a Function by Reference

    In PHP there are two ways you can pass arguments to a function: by value and by reference. By default, function arguments are passed by value so that if the value of the argument within the function is changed, it does not get affected outside of the function. However, to allow a function to modify its arguments, they must be passed by reference.

    Passing an argument by reference is done by prepending an ampersand (&) to the argument name in the function definition, as shown in the example below:

    Example

    <?php
    /* Defining a function that multiply a number
    by itself and return the new value */
    function selfMultiply(&$number){
        $number *= $number;
        return $number;
    }
     
    $mynum = 5;
    echo $mynum; // Outputs: 5
     
    selfMultiply($mynum);
    echo $mynum; // Outputs: 25
    ?>

    Understanding the Variable Scope

    However, you can declare the variables anywhere in a PHP script. But, the location of the declaration determines the extent of a variable’s visibility within the PHP program i.e. where the variable can be used or accessed. This accessibility is known as variable scope.

    By default, variables declared within a function are local and they cannot be viewed or manipulated from outside of that function, as demonstrated in the example below:

    Example

    <?php
    // Defining function
    function test(){
        $greet = "Hello World!";
        echo $greet;
    }
     
    test(); // Outputs: Hello World!
     
    echo $greet; // Generate undefined variable error
    ?>

    Similarly, if you try to access or import an outside variable inside the function, you’ll get an undefined variable error, as shown in the following example:

    Example

    <?php
    $greet = "Hello World!";
     
    // Defining function
    function test(){
        echo $greet;
    }
     
    test();  // Generate undefined variable error
     
    echo $greet; // Outputs: Hello World!
    ?>

    As you can see in the above examples the variable declared inside the function is not accessible from outside, likewise the variable declared outside of the function is not accessible inside of the function. This separation reduces the chances of variables within a function getting affected by the variables in the main program.

    Tip: It is possible to reuse the same name for a variable in different functions, since local variables are only recognized by the function in which they are declared.

    The global Keyword

    There may be a situation when you need to import a variable from the main program into a function, or vice versa. In such cases, you can use the global keyword before the variables inside a function. This keyword turns the variable into a global variable, making it visible or accessible both inside and outside the function, as show in the example below:

    Example

    <?php
    $greet = "Hello World!";
     
    // Defining function
    function test(){
        global $greet;
        echo $greet;
    }
     
    test(); // Outpus: Hello World!
    echo $greet; // Outpus: Hello World!
     
    // Assign a new value to variable
    $greet = "Goodbye";
     
    test(); // Outputs: Goodbye
    echo $greet; // Outputs: Goodbye
    ?>

    You will learn more about visibility and access control in PHP classes and objects chapter.


    Creating Recursive Functions

    A recursive function is a function that calls itself again and again until a condition is satisfied. Recursive functions are often used to solve complex mathematical calculations, or to process deeply nested structures e.g., printing all the elements of a deeply nested array.

    The following example demonstrates how a recursive function works.

    Example

    <?php
    // Defining recursive function
    function printValues($arr) {
        global $count;
        global $items;
        
        // Check input is an array
        if(!is_array($arr)){
            die("ERROR: Input is not an array");
        }
        
        /*
        Loop through array, if value is itself an array recursively call the
        function else add the value found to the output items array,
        and increment counter by 1 for each value found
        */
        foreach($arr as $a){
            if(is_array($a)){
                printValues($a);
            } else{
                $items[] = $a;
                $count++;
            }
        }
        
        // Return total count and values found in array
        return array('total' => $count, 'values' => $items);
    }
     
    // Define nested array
    $species = array(
        "birds" => array(
            "Eagle",
            "Parrot",
            "Swan"
        ),
        "mammals" => array(
            "Human",
            "cat" => array(
                "Lion",
                "Tiger",
                "Jaguar"
            ),
            "Elephant",
            "Monkey"
        ),
        "reptiles" => array(
            "snake" => array(
                "Cobra" => array(
                    "King Cobra",
                    "Egyptian cobra"
                ),
                "Viper",
                "Anaconda"
            ),
            "Crocodile",
            "Dinosaur" => array(
                "T-rex",
                "Alamosaurus"
            )
        )
    );
     
    // Count and print values in nested array
    $result = printValues($species);
    echo $result['total'] . ' value(s) found: ';
    echo implode(', ', $result['values']);
    ?>
  • PHP Loops

    Different Types of Loops in PHP

    Loops are used to execute the same block of code again and again, as long as a certain condition is met. The basic idea behind a loop is to automate the repetitive tasks within a program to save the time and effort. PHP supports four different types of loops.

    • while — loops through a block of code as long as the condition specified evaluates to true.
    • do…while — the block of code executed once and then condition is evaluated. If the condition is true the statement is repeated as long as the specified condition is true.
    • for — loops through a block of code until the counter reaches a specified number.
    • foreach — loops through a block of code for each element in an array.

    You will also learn how to loop through the values of array using foreach() loop at the end of this chapter. The foreach() loop work specifically with arrays.


    PHP while Loop

    The while statement will loops through a block of code as long as the condition specified in the while statement evaluate to true.

    while(condition){
        // Code to be executed
    }

    The example below define a loop that starts with $i=1. The loop will continue to run as long as $i is less than or equal to 3. The $i will increase by 1 each time the loop runs:

    Example

    <?php
    $i = 1;
    while($i <= 3){
        $i++;
        echo "The number is " . $i . "<br>";
    }
    ?>

    PHP do…while Loop

    The do-while loop is a variant of while loop, which evaluates the condition at the end of each loop iteration. With a do-while loop the block of code executed once, and then the condition is evaluated, if the condition is true, the statement is repeated as long as the specified condition evaluated to is true.

    do{
        // Code to be executed
    }
    while(condition);

    The following example define a loop that starts with $i=1. It will then increase $i with 1, and print the output. Then the condition is evaluated, and the loop will continue to run as long as $i is less than, or equal to 3.

    Example

    <?php
    $i = 1;
    do{
        $i++;
        echo "The number is " . $i . "<br>";
    }
    while($i <= 3);
    ?>

    Difference Between while and do…while Loop

    The while loop differs from the do-while loop in one important way — with a while loop, the condition to be evaluated is tested at the beginning of each loop iteration, so if the conditional expression evaluates to false, the loop will never be executed.

    With a do-while loop, on the other hand, the loop will always be executed once, even if the conditional expression is false, because the condition is evaluated at the end of the loop iteration rather than the beginning.


    PHP for Loop

    The for loop repeats a block of code as long as a certain condition is met. It is typically used to execute a block of code for certain number of times.

    for(initialization; condition; increment){
        // Code to be executed
    }

    The parameters of for loop have following meanings:

    • initialization — it is used to initialize the counter variables, and evaluated once unconditionally before the first execution of the body of the loop.
    • condition — in the beginning of each iteration, condition is evaluated. If it evaluates to true, the loop continues and the nested statements are executed. If it evaluates to false, the execution of the loop ends.
    • increment — it updates the loop counter with a new value. It is evaluate at the end of each iteration.

    The example below defines a loop that starts with $i=1. The loop will continued until $i is less than, or equal to 3. The variable $i will increase by 1 each time the loop runs:

    Example

    <?php
    for($i=1; $i<=3; $i++){
        echo "The number is " . $i . "<br>";
    }
    ?>

    PHP foreach Loop

    The foreach loop is used to iterate over arrays.

    foreach($array as $value){
        // Code to be executed
    }

    The following example demonstrates a loop that will print the values of the given array:

    Example

    <?php
    $colors = array("Red", "Green", "Blue");
     
    // Loop through colors array
    foreach($colors as $value){
        echo $value . "<br>";
    }
    ?>

    There is one more syntax of foreach loop, which is extension of the first.

    foreach($array as $key => $value){
        // Code to be executed
    }

    Example

    <?php
    $superhero = array(
        "name" => "Peter Parker",
        "email" => "[email protected]",
        "age" => 18
    );
     
    // Loop through superhero array
    foreach($superhero as $key => $value){
        echo $key . " : " . $value . "<br>";
    }
    ?>
  • PHP Sorting Arrays

    PHP Functions For Sorting Arrays

    In the previous chapter you’ve learnt the essentials of PHP arrays i.e. what arrays are, how to create them, how to view their structure, how to access their elements etc. You can do even more things with arrays like sorting the elements in any order you like.

    PHP comes with a number of built-in functions designed specifically for sorting array elements in different ways like alphabetically or numerically in ascending or descending order. Here we’ll explore some of these functions most commonly used for sorting arrays.

    • sort() and rsort() — For sorting indexed arrays
    • asort() and arsort() — For sorting associative arrays by value
    • ksort() and krsort() — For sorting associative arrays by key

    Sorting Indexed Arrays in Ascending Order

    The sort() function is used for sorting the elements of the indexed array in ascending order (alphabetically for letters and numerically for numbers).

    Example

    <?php
    // Define array
    $colors = array("Red", "Green", "Blue", "Yellow");
     
    // Sorting and printing array
    sort($colors);
    print_r($colors);
    ?>

    This print_r() statement gives the following output:

    Array ( [0] => Blue [1] => Green [2] => Red [3] => Yellow )

    Similarly you can sort the numeric elements of the array in ascending order.

    Example

    <?php
    // Define array
    $numbers = array(1, 2, 2.5, 4, 7, 10);
     
    // Sorting and printing array
    sort($numbers);
    print_r($numbers);
    ?>

    This print_r() statement gives the following output:

    Array ( [0] => 1 [1] => 2 [2] => 2.5 [3] => 4 [4] => 7 [5] => 10 )


    Sorting Indexed Arrays in Descending Order

    The rsort() function is used for sorting the elements of the indexed array in descending order (alphabetically for letters and numerically for numbers).

    Example

    <?php
    // Define array
    $colors = array("Red", "Green", "Blue", "Yellow");
     
    // Sorting and printing array
    rsort($colors);
    print_r($colors);
    ?>

    This print_r() statement gives the following output:

    Array ( [0] => Yellow [1] => Red [2] => Green [3] => Blue )

    Similarly you can sort the numeric elements of the array in descending order.

    Example

    <?php
    // Define array
    $numbers = array(1, 2, 2.5, 4, 7, 10);
     
    // Sorting and printing array
    rsort($numbers);
    print_r($numbers);
    ?>

    This print_r() statement gives the following output:

    Array ( [0] => 10 [1] => 7 [2] => 4 [3] => 2.5 [4] => 2 [5] => 1 )


    Sorting Associative Arrays in Ascending Order By Value

    The asort() function sorts the elements of an associative array in ascending order according to the value. It works just like sort(), but it preserves the association between keys and its values while sorting.

    Example

    <?php
    // Define array
    $age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
     
    // Sorting array by value and print
    asort($age);
    print_r($age);
    ?>

    This print_r() statement gives the following output:

    Array ( [Harry] => 14 [Peter] => 20 [Clark] => 35 [John] => 45 )


    Sorting Associative Arrays in Descending Order By Value

    The arsort() function sorts the elements of an associative array in descending order according to the value. It works just like rsort(), but it preserves the association between keys and its values while sorting.

    Example

    <?php
    // Define array
    $age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
     
    // Sorting array by value and print
    arsort($age);
    print_r($age);
    ?>

    This print_r() statement gives the following output:

    Array ( [John] => 45 [Clark] => 35 [Peter] => 20 [Harry] => 14 )


    Sorting Associative Arrays in Ascending Order By Key

    The ksort() function sorts the elements of an associative array in ascending order by their keys. It preserves the association between keys and its values while sorting, same as asort() function.

    Example

    <?php
    // Define array
    $age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
     
    // Sorting array by key and print
    ksort($age);
    print_r($age);
    ?>

    This print_r() statement gives the following output:

    Array ( [Clark] => 35 [Harry] => 14 [John] => 45 [Peter] => 20 )


    Sorting Associative Arrays in Descending Order By Key

    The krsort() function sorts the elements of an associative array in descending order by their keys. It preserves the association between keys and its values while sorting, same as arsort() function.

    Example

    <?php
    // Define array
    $age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
     
    // Sorting array by key and print
    krsort($age);
    print_r($age);
    ?>

    This print_r() statement gives the following output:

    Array ( [Peter] => 20 [John] => 45 [Harry] => 14 [Clark] => 35 )

  • PHP Arrays

    What is PHP Arrays

    Arrays are complex variables that allow us to store more than one value or a group of values under a single variable name. Let’s suppose you want to store colors in your PHP script. Storing the colors one by one in a variable could look something like this:

    Example

    <?php
    $color1 = "Red";
    $color2 = "Green";
    $color3 = "Blue";
    ?>

    But what, if you want to store the states or city names of a country in variables and this time this not just three may be hundred. It is quite hard, boring, and bad idea to store each city name in a separate variable. And here array comes into play.


    Types of Arrays in PHP

    There are three types of arrays that you can create. These are:

    • Indexed array — An array with a numeric key.
    • Associative array — An array where each key has its own specific value.
    • Multidimensional array — An array containing one or more arrays within itself.

    Indexed Arrays

    An indexed or numeric array stores each array element with a numeric index. The following examples shows two ways of creating an indexed array, the easiest way is:

    Example

    <?php
    // Define an indexed array
    $colors = array("Red", "Green", "Blue");
    ?>

    Note: In an indexed or numeric array, the indexes are automatically assigned and start with 0, and the values can be any data type.

    This is equivalent to the following example, in which indexes are assigned manually:

    Example

    <?php
    $colors[0] = "Red"; 
    $colors[1] = "Green"; 
    $colors[2] = "Blue"; 
    ?>

    Associative Arrays

    In an associative array, the keys assigned to values can be arbitrary and user defined strings. In the following example the array uses keys instead of index numbers:

    Example

    <?php
    // Define an associative array
    $ages = array("Peter"=>22, "Clark"=>32, "John"=>28);
    ?>

    The following example is equivalent to the previous example, but shows a different way of creating associative arrays:

    Example

    <?php
    $ages["Peter"] = "22";
    $ages["Clark"] = "32";
    $ages["John"] = "28";
    ?>

    Multidimensional Arrays

    The multidimensional array is an array in which each element can also be an array and each element in the sub-array can be an array or further contain array within itself and so on. An example of a multidimensional array will look something like this:

    Example

    <?php
    // Define a multidimensional array
    $contacts = array(
        array(
            "name" => "Peter Parker",
            "email" => "[email protected]",
        ),
        array(
            "name" => "Clark Kent",
            "email" => "[email protected]",
        ),
        array(
            "name" => "Harry Potter",
            "email" => "[email protected]",
        )
    );
    // Access nested value
    echo "Peter Parker's Email-id is: " . $contacts[0]["email"];
    ?>

    Viewing Array Structure and Values

    You can see the structure and values of any array by using one of two statements — var_dump() or print_r(). The print_r() statement, however, gives somewhat less information. Consider the following example:

    Example

    <?php
    // Define array
    $cities = array("London", "Paris", "New York");
     
    // Display the cities array
    print_r($cities);
    ?>

    The print_r() statement gives the following output:

    Array ( [0] => London [1] => Paris [2] => New York )

    This output shows the key and the value for each element in the array. To get more information, use the following statement:

    Example

    <?php
    // Define array
    $cities = array("London", "Paris", "New York");
     
    // Display the cities array
    var_dump($cities);
    ?>

    This var_dump() statement gives the following output:

    array(3) { [0]=> string(6) “London” [1]=> string(5) “Paris” [2]=> string(8) “New York” }

    This output shows the data type of each element, such as a string of 6 characters, in addition to the key and value. In the next chapter you will learn how to sort array elements.