Quick Contact

    Introducing Functions
    What is a Function?

    A function is just a segment of code, separate from the rest of your code. You separate it because it’s nice and handy, and you want to use it not once but over and over. It’s a chunk of code that you think is useful and want to use again. Functions save you from writing the code over and over.

    Here’s an example.

    Suppose you need to check text from a textbox. You want to trim any blank spaces from the left and right of the text that the user entered. So, if they entered this:

    Bill Gates 

    You want to turn it into this:

    Bill Gates

    But you also want to check if the user entered any text at all. You don’t want the textbox to be completely blank!

    You can use the PHP inbuilt function called trim (). Like this:

    $user_text = trim($_POST['text1'] );

    That will get rid of the white space in the text box. But it won’t check if the text box is blank. You can add an if statement for that:

    if ($user_text == "") {
    error_message = "Blank textbox detected";
    }

    But what if you have lots of textboxes on your form? You’d have to have lots of if statements and check each single variable for a blank string. That’s a lot of code to write!

    Rather than do that, you can create a single function, with one if statement that can be used for each blank string you need to check. Using a function means there’s less code for you to write. And it’s more efficient. We’ll see how to write a function for the above scenario in a moment. But first, here’s the basic syntax for a function.

    function function_name() {
    }
    

    So you start by typing the word function. You then need to come up with a name for your function. You can call almost anything you like. It’s just like a variable name. Next, you type two round brackets ( ). Finally, you need the two curly brackets as well { }.

    Whatever you function does goes between the curly brackets. Here’s a simple example that just print something out:

    function display_error_message() {
    print "Error Detetceted";
    }
    

    In the example above, we’ve started with function. We’ve then called this particular function display_error_message. In between the curly brackets, there a print statement.

    Try it out with this script:
    <?PHP
    function display_error_message( ) {
    print "Error Detetceted";
    }
    ?>
    

    Run your script and see what happens. You should find that nothing happens!

    The reason that nothing happened is because a function is a separate piece of code. It doesn’t run until you tell it to. Just loading the script won’t work. It’s like those inbuilt functions you used, such as trim. You can’t use trim( ) unless you type out the name, and what you want PHP to trim. The same applies to your own functions – you have to “tell” PHP that you want to use a function that you wrote. You do this by simply typing out the name of your function. This is known as “calling” a function.

    Try this new version of the script.
    <?PHP
    function display_error_message() {
    print "Error Detetceted";
    }
    display_error_message( );
    ?>
    

    After the function, we’ve typed out the name again. This is enough to tell PHP to run our code segment. Now change your code to this, and see what happens:

    <?PHP
    display_error_message();
    function display_error_message() {
    print "Error Detetceted";
    }
    ?>
    

    When you run the code, you should see no difference – the function will still get executed with the name above or below the function. But for neatness and readability’s sake, it’s better to put all of your function either at the top or bottom of your scripts. Or better yet, in a separate PHP file. You can then use another inbuilt function called “Include” (which we’ll get to soon).

    Defining functions

    PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.A function is a self-contained block of code that performs a specific task.Functions can either return values when called or can simply perform an operation without returning any value.

    Why uses Functions?
    • Better code organization: functions allow us to group blocks of related code that perform a specific task together.
    • Reusability: once defined, a function can be called by a number of scripts in our PHP files. This saves us time of reinventing the wheel when we want to perform some routine tasks such as connecting to the database
    • Easy maintenance: updates to the system only need to be made in one place.
    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.

    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.

    A user-defined function declaration starts with the word function:

    Syntax:
    function functionName () {
    //code to be executed;
    }
    

    Note: A function name can start with a letter or underscore (not a number).

    Creating and Invoking Functions

    Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it. Following example creates a function called writeMessage () and then calls it just after creating it.

    Note: that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below:

    <html>
    <head>
    <title>Writing PHP Function</title>
    </head>
    <body>
    <?php
    /* Defining a PHP Function */
    function writeMessage () {
    echo "You are really a nice person, Have a nice time!";
    }
    /* Calling a PHP Function */
    writeMessage ();
    ?>
    </body>
    </html>
    

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

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

    Before creating first user defined function, let’s look at the rules that you must follow when creating your own functions:

    • Function names must start with a letter or an underscore but not a number
    • The function name must be unique
    • The function name must not contain spaces
    • It is considered a good practice to use descriptive function names.
    • Functions can optionally accept parameters and return values too.
    Using parameters

    PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like.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.

    Following example takes two integer parameters and add them together and then print them:
    <html>
    <head>
    <title>Writing PHP Function with Parameters</title>
    </head>
    <body>
    <?php
    function addFunction($num1, $num2) {
    $sum = $num1 + $num2;
    echo "Sum of the two numbers is : $sum";
    }
    addFunction(10, 20);
    ?>
    </body>
    </html>
    
    This will display following result:

    Sum of the two numbers is: 30

    Note: 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

    The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument:

    <html>
    <body>
    
    <?php
    function setHeight($minheight = 50) {
        echo "The height is : $minheight <br>";
    }
    setHeight(350);
    setHeight();
    setHeight(135);
    setHeight(80);
    ?>
    </body>
    </html>
    
    This will display following result:

    The height is: 350

    The height is: 50

    The height is: 135

    The height is: 80

    Understanding scope

    Scope of a variable is defined as its extent in program within which it can be accessed, i.e. the scope of a variable is the portion of the program with in which it is visible or can be accessed.

    Depending on the scopes, there are only two scopes available in PHP namely local and global scopes.Variable scope is known as its boundary within which it can be visible or accessed from code.

    • Local variables (local scope)
    • Global variables (special global scope)
    • Static variables (local scope)
    • Function parameters (local scope)

    When a variable is accessed outside its scope it will cause PHP error Undefined Variable.

    Local variables:

    The variables declared within a function are called local variables to that function and has its scope only in that particular function. In simple words it cannot be accessed outside that function. Any declaration of a variable outside the function with same name as that of the one within the function is a complete different variable. We will learn about functions in details in later articles. For now, consider a function as a block of statements.

    Example:
    <?php
    $num = 60;
    function local_var()
    {
    // This $num is local to this function
    // the variable $num outside this function
    // is a completely different variable
    $num = 50;
    echo "local num = $num \n";
    }
    local_var();
    // $num outside function local_var() is a
    // completely different Variable than that of
    // inside local_var()
    echo "Variable num outside local_var() is $num \n";
    ?>
    
    Output:

    local num = 50

    Variable num outside local_var() is 60

    Global variables:

    The variables declared outside a function are called global variables. These variables can be accessed directly outside a function. To get access within a function we need to use the “global” keyword before the variable to refer to the global variable.

    Example:
    <?php
    $num = 20;
    // function to demonstrate use of global variable
    function global_var()
    {
    // we have to use global keyword before
    // the variable $num to access within
    // the function
    global $num;
    echo "Variable num inside function : $num \n";
    }
    global_var();
    echo "Variable num outside function : $num \n";
    ?>
    
    Output:

    Variable num inside function: 20

    Variable num outside function: 20

    Static variable:

    It is the characteristic of PHP to delete the variable, ones it completes its execution and the memory is freed. But sometimes we need to store the variables even after the completion of function execution. To do this we use static keyword and the variables are then called as static variables.

    Example:
    <?php
    // function to demonstrate static variables
    function static_var()
    {
    // static variable
    static $num = 5;
    $sum = 2;
    $sum++;
    $num++;
    echo $num, "\n";
    echo $sum, "\n";
    }
    // first function call
    static_var();
    // second function call
    static_var();
    ?>
    
    Output:

    6

    3

    7

    3

    You must have noticed that $num regularly increments even after the first function call but $sum doesn’t. This is because $sum is not static and its memory is freed after execution of first function call.

    Function Parameters (Local Scope)

    Function parameters (arguments) are local variables defined within the local scope of the function on which it is used as the argument.

    Scope and File Includes

    The boundary of file includes does not demarcate the scope of variables. The scope of a variable is only governed by the function block and not based on the file include. A variable can be declared in a PHP file and used in another file by using ‘include’ or ‘require’ that file.

    Function Inside Function or Class

    Remember that the scope in PHP is governed by a function block. Any new function declared anywhere starts a new scope. If an anonymous function is defined inside another function, the anonymous function has its own local scope.

    <?php
    function foo() {
        $fruit = 'apple';
        $bar = function () {
    // $fruit cannot be accessed inside here
            $animal = 'lion';
        };
        // $animal cannot be accessed outside here
    }
    ?>
    

    In the above example code, $fruit variable is restricted to the outer function and its scope does not span inside the anonymous inner function. The same way, $animal which is declared inside is not accessible in the outer function as its scope boundary is restricted to the inner function.

    Returning values

    Values are returned by using the optional return statement. Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called.

    Call by Value

    Call by value means passing the value directly to a function. The called function uses the value in a local variable; any changes to it do not affect the source variable.PHP allows you to call function by value and reference both.

    Let’s understand the concept of call by value by the help of examples.

    In this example, variable $str is passed to the adder function where it is concatenated with ‘Call By Value’ string. But, printing $str variable results ‘Hello’ only. It is

    because changes are done in the local variable $str2 only. It doesn’t reflect to $str variable.

    <?php  
    function adder($str2)  
    {  
        $str2 .= 'Call By Value';  
    }  
    $str = 'Hello ';  
    adder($str);  
    echo $str;  
    ?>
    
    Call 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:

    <html lang="en">
    <head>
    <title>PHP Passing Arguments by Reference</title>
    </head>
    <body>
    <?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 . "<br>"; // Outputs: 5
    selfMultiply($mynum);
    echo $mynum . "<br>"; // Outputs: 25
    ?>
    </body>
    </html>
    
    Output:

    5

    25

    Difference between call by value and call by reference in PHP

    • Call by value means passing the value directly to a function. The called function uses the value in a local variable; any changes to it do not affect the source variable.
    • Call by reference means passing the address of a variable where the actual value is stored. The called function uses the value stored in the passed address; any changes to it do affect the source variable.
    Reusing Codes

    In programming, reusable code is the use of similar code in multiple functions.No, not by copying and then pasting the same code from one block to another and from there to another and so on. Instead, code reusability defines the methodology you can use to use similar code, without having to re-write it everywhere. As I have already said, not in a way to copy and paste it.There are many techniques to make code reusable in your applications.

    There are several advantages to code reuse and they include: reduces the cost (you will spend more time maintaining your code than writing it, therefore you want to make sure that you limit the number of lines in use.). In simple terms, less code means lower cost. Secondly, there is reliability – existing mature code is always more reliable than a fresh ‘green’ code.

    By the help of include and require construct, we can reuse HTML code or PHP script in many PHP scripts.

    Implementing recursion
    What is Recursion?

    The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily.There’s nearly always an end condition of some sort — known as the base case — otherwise the function would continue to call itself indefinitely (or at least until the computer ran out of memory).

    In other words, Recursion is a method of solving problems that involves breaking a problem down into smaller and smaller subproblems until you get to a small enough problem that it can be solved trivially. Usually recursion involves a function calling itself. While it may not seem like much on the surface, recursion allows us to write elegant solutions to problems that may otherwise be very difficult to program.

    Sometimes a problem is too difficult or too complex to solve because it is too big. If the problem can be broken down into smaller versions of itself, we may be able to find a way to solve one of these smaller versions and then be able to build up to a solution to the entire problem. This is the idea behind recursion; recursive algorithms break down a problem into smaller pieces which you either already know the answer to or can solve by applying the same algorithm to each piece, and then combining the results.

    Why Stack Overflow error occurs in recursion?

    If base case is not reached or not defined, then stack overflow problem may arise. Let us take an example to understand this.

    If fact (10) is called, it will call fact (9), fact (8), fact (7) and so on but number will never reach 100. So, the base case is not reached. If the memory is exhausted by these functions on stack, it will cause stack overflow error.

    Care must be taken in PHP, however, as your code must not carry out a certain number of recursive function calls. i.e. There must be a mechanism (IF statement, etc.) that stops the recursion after the desired result has been found. If you allow your function to carry out an unlimited amount of calls you will receive the error: Fatal error: Maximum function nesting level of ‘100’ reached, aborting.

    How to implement a recursive function in PHP

    In general terms, a recursive function works like this:

    • The calling code calls the recursive function.
    • The function does any processing or calculations required.
    • If the base case has not yet been reached, the function calls itself to continue the recursion. This creates a new instance of the function.
    • If the base case is reached, the function just returns control to the code that called it, thereby ending the recursion.
    In pseudocode, a simple recursive function looks something like this:
    function myRecursiveFunction() {
    
    // (do the required processing...)
    
      if ( baseCaseReached ) {
    
    // end the recursion
        return;
    
      } else {
    
    // continue the recursion
        myRecursiveFunction();
    }
    
    The best way to understand recursive functions is by looking at some practical example. Let’s explore below example that show how recursion works in PHP:
    • Factorials
    • Checks to see if the number is less than 50
    Let’s write a recursive function to calculate the factorial for a given number, n:
    <?php
    function factorial( $n ) {
    // Base case
    if ( $n == 0 ) {
    echo "Base case: \$n = 0. Returning 1...<br>";
    return 1;
    }
    // Recursion
    echo "\$n = $n: Computing $n * factorial( " . ($n-1) . " )...<br>";
    $result = ( $n * factorial( $n-1 ) );
    echo "Result of $n * factorial( " . ($n-1) . " ) = $result. Returning $result...<br>";
    return $result;
    }
    echo "The factorial of 5 is: " . factorial( 5 );
    ?>
    
    As you can see, this function is pretty simple. Let’s break it down:
    1. Begin the function
    function factorial( $n ) {

    First, we define the function, factorial (), and include a parameter, $n, to hold the number that we want to calculate the factorial for.

    2. Set up the base case
    // Base case
    if ( $n == 0 ) {
      echo "Base case: \$n = 0. Returning 1...<br>";
      return 1;
    }
    

    Within our function, we first define the base case, which is when the supplied value, $n, equals 0. If this is the case then we’ve reached the end of our recursion, and we simply return 1 (the factorial of 0 is 1). This value is returned to the code that called it, which will be either another instance of the factorial() function, or the outside calling code.

    3. Do the recursion
    // Recursion
      echo "\$n = $n: Computing $n * factorial( " . ($n-1) . " )...<br>";
      $result = ( $n * factorial( $n-1 ) );
      echo "Result of $n * factorial( " . ($n-1) . " ) = $result. Returning $result...<br>";
      return $result;
    }
    

    The last block of code in the function performs the actual recursion, and it’s run as long as $n is greater than zero. It calls itself, passing in $n-1 as the argument, and multiplies the resulting value by $n. In other words, it computes the factorial of the integer that is 1 less than the current value, then multiplies this by the current value to get the current value’s factorial. It then stores this value in $result and returns it to the calling code.

    4. Test the function
    echo "The factorial of 5 is: " . factorial( 5 );

    Finally, we test our function by calling it with a value of 5. This produces the correct result (120).

    Let’s write a recursive function Checks to see if the number is less than 50:
    //Our recursive function.
    function recursive($num){
    //Print out the number.
        echo $num, '<br>';
        //If the number is less or equal to 50.
        if($num < 50){
    //Call the function again. Increment number by one.
            return recursive($num + 1);
        }
    }
    //Set our start number to 1.
    $startNum = 1;
    //Call our recursive function.
    recursive($startNum);
    

    The code above is pretty simple. Basically, the function checks to see if the number is less than 50. If the number is less than 50, then we increment the number and call the function again. This process is repeated until the number has reached 50.

    Using Require () and include ()

    You can include the content of a PHP file into another PHP file before the server executes it. There are two PHP functions which can be used to included one PHP file into another PHP file.

    • The include() Function
    • The require() Function

    This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be reused on multiple pages. This will help developers to make it easy to change the layout of complete website with minimal effort. If there is any change required then instead of changing thousands of files just change included file.

    The include() Function

    The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.

    Syntax:
    include(File-name);
    Example:
    include (“header.php”)

    Assume you want to create a common menu for your website. Then create a file menu.php with the following content.

    <a href="http://www.tutorialspoint.com/index.htm">Home</a> - 
    <a href="http://www.tutorialspoint.com/ebxml">ebXML</a> - 
    <a href="http://www.tutorialspoint.com/ajax">AJAX</a> - 
    <a href="http://www.tutorialspoint.com/perl">PERL</a><br />
    

    Now create as many pages as you like and include this file to create header. For example now your test.php file can have following content.

    <html>
    <body>
    <?php include("menu.php"); ?>
    <p>This is an example to show how to include PHP file!</p>
    </body>
    </html>
    
    It will produce the following result:

    The require() Function

    The require() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.

    So there is no difference in require() and include() except they handle error conditions. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.

    Syntax:
    require(File-name);
    Example:
    require(“header.php”);

    You can try using above example with require() function and it will generate same result. But if you will try following two examples where file does not exist then you will get different results.

    <html>
    <body>
    <?php include("xxmenu.php"); ?>
    <p>This is an example to show how to include wrong PHP file!</p>
    </body>
    </html>
    
    This will produce the following result:

    This is an example to show how to include wrong PHP file!

    Now let’s try same example with require() function.

    <html>
    <body>
    <?php require("xxmenu.php"); ?>
    <p>This is an example to show how to include wrong PHP file!</p>
    </body>
    </html>
    

    This time file execution halts and nothing is displayed.

    Difference between include() and require() in PHP :
    • include() function takes one argument , a path/name of the specified file you want to include.
    • require() function performs the similar functionality as include() function, takes one argument i.e. path/name of the file you want to include.
    • include() function does not stop execution , just give warning and continues to execute the script in case of file name not found i..e missing/misnamed files .
    • require() function gives fatal error if it founds any problem like file not found or misnamed files and stops the execution once get fatal error.
    • The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.
    Array, String, Math, Date functions
    Array Functions?

    The array functions allow you to access and manipulate arrays.

    Simple and multi-dimensional arrays are supported.

    Installation

    There is no installation needed to use these functions; they are part of the PHP core.

    PHP Array Functions

    Arrays are essential for storing, managing, and operating on sets of variables.These functions allow you to interact with and manipulate arrays in various ways.

    Function Description
    array() Creates an array
    array_change_key_case() Changes all keys in an array to lowercase or uppercase
    array_chunk() Splits an array into chunks of arrays
    array_column() Returns the values from a single column in the input array
    array_combine() Creates an array by using the elements from one “keys” array and one “values” array
    array_count_values() Counts all the values of an array
    array_diff() Compare arrays, and returns the differences (compare values only)
    array_diff_assoc() Compare arrays, and returns the differences (compare keys and values)
    array_diff_key() Compare arrays, and returns the differences (compare keys only)
    array_diff_uassoc() Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function)
    array_diff_ukey() Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function)
    array_fill() Fills an array with values
    array_fill_keys() Fills an array with values, specifying keys
    array_filter() Filters the values of an array using a call back function
    array_flip() Flips/Exchanges all keys with their associated values in an array
    array_intersect() Compare arrays, and returns the matches (compare values only)
    array_intersect_assoc() Compare arrays and returns the matches (compare keys and values)
    array_intersect_key() Compare arrays, and returns the matches (compare keys only)
    array_intersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using a user-defined key comparison function)
    array_intersect_ukey() Compare arrays, and returns the matches (compare keys only, using a user-defined key comparison function)
    array_key_exists() Checks if the specified key exists in the array
    array_keys() Returns all the keys of an array
    array_map() Sends each value of an array to a user-made function, which returns new values
    array_merge() Merges one or more arrays into one array
    array_merge_recursive() Merges one or more arrays into one array recursively
    array_multisort() Sorts multiple or multi-dimensional arrays
    array_pad() Inserts a specified number of items, with a specified value, to an array
    array_pop() Deletes the last element of an array
    array_product() Calculates the product of the values in an array
    array_push() Inserts one or more elements to the end of an array
    array_rand() Returns one or more random keys from an array
    array_reduce() Returns an array as a string, using a user-defined function
    array_replace() Replaces the values of the first array with the values from following arrays
    array_replace_recursive() Replaces the values of the first array with the values from following arrays recursively
    array_reverse() Returns an array in the reverse order
    array_search() Searches an array for a given value and returns the key
    array_shift() Removes the first element from an array, and returns the value of the removed element
    array_slice() Returns selected parts of an array
    array_splice() Removes and replaces specified elements of an array
    array_sum() Returns the sum of the values in an array
    array_udiff() Compare arrays, and returns the differences (compare values only, using a user-defined key comparison function)
    array_udiff_assoc() Compare arrays, and returns the differences (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
    array_udiff_uassoc() Compare arrays, and returns the differences (compare keys and values, using two user-defined key comparison functions)
    array_uintersect() Compare arrays, and returns the matches (compare values only, using a user-defined key comparison function)
    array_uintersect_assoc() Compare arrays, and returns the matches (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
    array_uintersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using two user-defined key comparison functions)
    array_unique() Removes duplicate values from an array
    array_unshift() Adds one or more elements to the beginning of an array
    array_values() Returns all the values of an array
    array_walk() Applies a user function to every member of an array
    array_walk_recursive() Applies a user function recursively to every member of an array
    arsort() Sorts an associative array in descending order, according to the value
    asort() Sorts an associative array in ascending order, according to the value
    compact() Create array containing variables and their values
    count() Returns the number of elements in an array
    current() Returns the current element in an array
    each() Returns the current key and value pair from an array
    end() Sets the internal pointer of an array to its last element
    extract() Imports variables into the current symbol table from an array
    in_array() Checks if a specified value exists in an array
    key() Fetches a key from an array
    krsort() Sorts an associative array in descending order, according to the key
    ksort() Sorts an associative array in ascending order, according to the key
    list() Assigns variables as if they were an array
    natcasesort() Sorts an array using a case insensitive “natural order” algorithm
    natsort() Sorts an array using a “natural order” algorithm
    next() Advance the internal array pointer of an array
    pos() Alias of current()
    prev() Rewinds the internal array pointer
    range() Creates an array containing a range of elements
    reset() Sets the internal pointer of an array to its first element
    rsort() Sorts an indexed array in descending order
    shuffle() Shuffles an array
    sizeof() Alias of count()
    sort() Sorts an indexed array in ascending order
    uasort() Sorts an array by values using a user-defined comparison function
    uksort() Sorts an array by keys using a user-defined comparison function
    usort() Sorts an array using a user-defined comparison function
    Math Functions

    The math functions can handle values within the range of integer and float types.The PHP math functions are part of the PHP core. No installation is required to use these functions.

    The following Math functions are the part of the PHP core so you can use these functions within your script without any further installation.

    Function Description
    abs() Returns the absolute (positive) value of a number
    acos() Returns the arc cosine of a number
    acosh() Returns the inverse hyperbolic cosine of a number
    asin() Returns the arc sine of a number
    asinh() Returns the inverse hyperbolic sine of a number
    atan() Returns the arc tangent of a number in radians
    atan2() Returns the arc tangent of two variables x and y
    atanh() Returns the inverse hyperbolic tangent of a number
    base_convert() Converts a number from one number base to another
    bindec() Converts a binary number to a decimal number
    ceil() Rounds a number up to the nearest integer
    cos() Returns the cosine of a number
    cosh() Returns the hyperbolic cosine of a number
    decbin() Converts a decimal number to a binary number
    dechex() Converts a decimal number to a hexadecimal number
    decoct() Converts a decimal number to an octal number
    deg2rad() Converts a degree value to a radian value
    exp() Calculates the exponent of e
    expm1() Returns exp(x) – 1
    floor() Rounds a number down to the nearest integer
    fmod() Returns the remainder of x/y
    getrandmax() Returns the largest possible value returned by rand()
    hexdec() Converts a hexadecimal number to a decimal number
    hypot() Calculates the hypotenuse of a right-angle triangle
    is_finite() Checks whether a value is finite or not
    is_infinite() Checks whether a value is infinite or not
    is_nan() Checks whether a value is ‘not-a-number’
    lcg_value() Returns a pseudo random number in a range between 0 and 1
    log() Returns the natural logarithm of a number
    log10() Returns the base-10 logarithm of a number
    log1p() Returns log(1+number)
    max() Returns the highest value in an array, or the highest value of several specified values
    min() Returns the lowest value in an array, or the lowest value of several specified values
    mt_getrandmax() Returns the largest possible value returned by mt_rand()
    mt_rand() Generates a random integer using Mersenne Twister algorithm
    mt_srand() Seeds the Mersenne Twister random number generator
    octdec() Converts an octal number to a decimal number
    pi() Returns the value of PI
    pow() Returns x raised to the power of y
    rad2deg() Converts a radian value to a degree value
    rand() Generates a random integer
    round() Rounds a floating-point number
    sin() Returns the sine of a number
    sinh() Returns the hyperbolic sine of a number
    sqrt() Returns the square root of a number
    srand() Seeds the random number generator
    tan() Returns the tangent of a number
    tanh() Returns the hyperbolic tangent of a number
    Function Description
    Function Description
    Function Description
    Date Functions

    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(format, timestamp)

    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:

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

    Super Global Array Variables

    The super global arrays in PHP will help you find cookies information, how to send secure data to server and upload files and create sessions which are variables that store information of user for later use.Super global arrays are predefined arrays and can be accessed anywhere in the page, without using the word global.

    These are specially-defined array variables in PHP that make it easy for you to get information about a request or its context.The superglobals are available throughout your script. These variables can be accessed from any function, class or any file without doing any special task such as declaring any global variable etc. They are mainly used to store and get information from one page to another etc. in an application.

    Below is the list of super global variables available in PHP:
    • $GLOBALS
    • $_SERVER
    • $_REQUEST
    • $_POST
    • $_GET
    • $_FILES
    • $_ENV
    • $_COOKIE
    • $_SESSION
    Let us now learn about some of these superglobals in details:

    $GLOBALS:It is a super global variable which is used to access global variables from anywhere in the PHP script. PHP stores all the global variables in array $GLOBALS [] it consists of an array which have an index that holds the global variable name, which can be accessed.

    Below program illustrates the use of $GLOBALS in PHP:
    <?php
    $x = 300;
    $y = 200;
    function multiplication(){
        $GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y'];
    }
    multiplication();
    echo $z;
    ?>
    
    Output:

    60000

    In the above code two global variables are declared $x and $y which are assigned some value to them. Then a function multiplication() is defined to multiply the values of $x and $y and store in another variable $z defined in the GLOBAL array.

    $_SERVER

    It is a PHP super global variable that stores the information about headers, paths and script locations. Some of these elements are used to get the information from the super global variable $_SERVER.

    Below program illustrates the use of $_SERVER in PHP:
    <html>
    <body>
    <?php 
    echo $_SERVER['PHP_SELF'];
    echo "<br>";
    echo $_SERVER['SERVER_NAME'];
    echo "<br>";
    echo $_SERVER['HTTP_HOST'];
    echo "<br>";
    echo $_SERVER['HTTP_REFERER'];
    echo "<br>";
    echo $_SERVER['HTTP_USER_AGENT'];
    echo "<br>";
    echo $_SERVER['SCRIPT_NAME'];
    ?>
    </body>
    </html>
    

    In the above code we used the $_SERVER elements to get some information. We get the current file name which is worked on using PHP_SELF element. Then we get server name used currently using SERVER_NAME element. And then we get the host name through HTTP_HOST.

    $_REQUEST

    It is a super global variable which is used to collect the data after submitting a HTML form. $_REQUEST is not used mostly, because $_POST and $_GET perform the same task and are widely used.

    Below is the HTML and PHP code to explain how $_REQUEST works:
    <!DOCTYPE html>
    <html>
    <body>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
     NAME: <input type="text" name="fname">
    <button type="submit">SUBMIT</button>
    </form>
    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $name = htmlspecialchars($_REQUEST['fname']);
        if(empty($name)){
            echo "Name is empty";
        } else {
            echo $name;
        }
    }
    ?>
    </body>
    </html>
    
    Output:

    In the above code we have created a form that takes the name as input from the user and prints its name on clicking of submit button. We transport the data accepted in the form to the same page using $_SERVER[‘PHP_SELF’] element as specified in the action attribute, because we manipulate the data in the same page using the PHP code. The data is retrieved using the $_REQUEST super global array variable

    $_POST

    It is a super global variable used to collect data from the HTML form after submitting it. When form uses method post to transfer data, the data is not visible in the query string, because of which security levels are maintained in this method.

    Below is the HTML and PHP code to explain how $_POST works:

    The example below shows a form with an input field and a submit button. When a user submits the data by clicking on “Submit”, the form data is sent to the file specified in the action attribute of the <form> tag. In this example, we point to the file itself for processing form data. If you wish to use another PHP file to process form data, replace that with the filename of your choice. Then, we can use the super global variable $_POST to collect the value of the input field:

    <html>
    <body>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
      Name: <input type="text" name="fname">
    <input type="submit">
    </form>
    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // collect value of input field
        $name = $_POST['fname'];
        if (empty($name)) {
            echo "Name is empty";
        } else {
            echo $name;
        }
    }
    ?>
    </body>
    </html>
    
    Output:

    $_GET

    $_GET is a super global variable used to collect data from the HTML form after submitting it. When form uses method get to transfer data, the data is visible in the query string, therefore the values are not hidden. $_GET super global array variable stores the values that come in the URL.

    Below is the HTML and PHP code to explain how $_GET works:
    <!DOCTYPE html>
    <html>
    <head>
    <title></title>
    </head>
    <body bgcolor="cyan">
    <?php
            $name = $_GET['name'];
            $city = $_GET['city'];
            echo "<h1>This is ".$name." of ".$city."</h1><br>";
        ?>
    <img src = "2.jpg" alt = "nanilake" height = "400" width="500" />
    </body>
    </html>
    

    We are actually seeing half of the logic just now. In the above code we have created a hyperlink image of Nainital Lake which will take us to picture. PHP page and with it will also take the paramerters name=Nainilakeand city=Nainital.

    That is when we click on the small image of Nainital Lake we will be taken to the next page picture.php along with the parameters. As the default method is get, these parameters will be passed to the next page using get method and they will be visible in the address bar. When we want to pass values to an address they are attached to the address using a question mark (?).

    Here the parameter name=Nainilake is attached to the address. If we want to add more values, we can add them using ampersand (&) after every key-value pair similarly as city=Nainital is added using ampersand after the name parameter. Now after clicking on the image of Nainital Lake we want the picture.php page to be displayed with the value of parameter displayed along with it.

    Summary
    • Functions are blocks of code that perform specific tasks
    • Built in functions are functions that are shipped with PHP
    • PHP has over 700 built in functions
    • User defined functions are functions that you can create yourself to enhance PHP
    • Information can be passed to functions through arguments. An argument is just like a variable.
    • By the help of include and require construct, we can reuse HTML code or PHP script in many PHP scripts.
    • Variable scope is known as its boundary within which it can be visible or accessed from code.
    • Super Global Array Variablesare mainly used to store and get information from one page to another etc. in an application.

    Enrolled Yourself – PHP Training 

    Copyright 1999- Ducat Creative, All rights reserved.