Category: PHP

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

  • PHP Switch…Case Statements

    PHP If…Else Vs Switch…Case

    The switch-case statement is an alternative to the if-elseif-else statement, which does almost the same thing. The switch-case statement tests a variable against a series of values until it finds a match, and then executes the block of code corresponding to that match.

    switch(n){
    case label1:
            // Code to be executed if n=label1
            break;
    case label2:
            // Code to be executed if n=label2
            break;
        …
    default:
            // Code to be executed if n is different from all labels
    }

    Consider the following example, which display a different message for each day.

    Example

    <?php
    $today = date("D");
    switch($today){
        case "Mon":
            echo "Today is Monday. Clean your house.";
            break;
        case "Tue":
            echo "Today is Tuesday. Buy some food.";
            break;
        case "Wed":
            echo "Today is Wednesday. Visit a doctor.";
            break;
        case "Thu":
            echo "Today is Thursday. Repair your car.";
            break;
        case "Fri":
            echo "Today is Friday. Party tonight.";
            break;
        case "Sat":
            echo "Today is Saturday. Its movie time.";
            break;
        case "Sun":
            echo "Today is Sunday. Do some rest.";
            break;
        default:
            echo "No information available for that day.";
            break;
    }
    ?>

    The switch-case statement differs from the if-elseif-else statement in one important way. The switch statement executes line by line (i.e. statement by statement) and once PHP finds a case statement that evaluates to true, it’s not only executes the code corresponding to that case statement, but also executes all the subsequent case statements till the end of the switch block automatically.

    To prevent this add a break statement to the end of each case block. The break statement tells PHP to break out of the switch-case statement block once it executes the code associated with the first true case.

  • PHP Operators

    What is Operators in PHP

    Operators are symbols that tell the PHP processor to perform certain actions. For example, the addition (+) symbol is an operator that tells PHP to add two variables or values, while the greater-than (>) symbol is an operator that tells PHP to compare two values.

    The following lists describe the different operators used in PHP.

    PHP Arithmetic Operators

    The arithmetic operators are used to perform common arithmetical operations, such as addition, subtraction, multiplication etc. Here’s a complete list of PHP’s arithmetic operators:

    OperatorDescriptionExampleResult
    +Addition$x + $ySum of $x and $y
    -Subtraction$x - $yDifference of $x and $y.
    *Multiplication$x * $yProduct of $x and $y.
    /Division$x / $yQuotient of $x and $y
    %Modulus$x % $yRemainder of $x divided by $y

    The following example will show you these arithmetic operators in action:

    Example

    <?php
    $x = 10;
    $y = 4;
    echo($x + $y); // 0utputs: 14
    echo($x - $y); // 0utputs: 6
    echo($x * $y); // 0utputs: 40
    echo($x / $y); // 0utputs: 2.5
    echo($x % $y); // 0utputs: 2
    ?>

    PHP Assignment Operators

    The assignment operators are used to assign values to variables.

    OperatorDescriptionExampleIs The Same As
    =Assign$x = $y$x = $y
    +=Add and assign$x += $y$x = $x + $y
    -=Subtract and assign$x -= $y$x = $x - $y
    *=Multiply and assign$x *= $y$x = $x * $y
    /=Divide and assign quotient$x /= $y$x = $x / $y
    %=Divide and assign modulus$x %= $y$x = $x % $y

    The following example will show you these assignment operators in action:

    Example

    <?php
    $x = 10;
    echo $x; // Outputs: 10
     
    $x = 20;
    $x += 30;
    echo $x; // Outputs: 50
     
    $x = 50;
    $x -= 20;
    echo $x; // Outputs: 30
     
    $x = 5;
    $x *= 25;
    echo $x; // Outputs: 125
     
    $x = 50;
    $x /= 10;
    echo $x; // Outputs: 5
     
    $x = 100;
    $x %= 15;
    echo $x; // Outputs: 10
    ?>

    PHP Comparison Operators

    The comparison operators are used to compare two values in a Boolean fashion.

    OperatorNameExampleResult
    ==Equal$x == $yTrue if $x is equal to $y
    ===Identical$x === $yTrue if $x is equal to $y, and they are of the same type
    !=Not equal$x != $yTrue if $x is not equal to $y
    <>Not equal$x <> $yTrue if $x is not equal to $y
    !==Not identical$x !== $yTrue if $x is not equal to $y, or they are not of the same type
    <Less than$x < $yTrue if $x is less than $y
    >Greater than$x > $yTrue if $x is greater than $y
    >=Greater than or equal to$x >= $yTrue if $x is greater than or equal to $y
    <=Less than or equal to$x <= $yTrue if $x is less than or equal to $y

    The following example will show you these comparison operators in action:

    Example

    <?php
    $x = 25;
    $y = 35;
    $z = "25";
    var_dump($x == $z);  // Outputs: boolean true
    var_dump($x === $z); // Outputs: boolean false
    var_dump($x != $y);  // Outputs: boolean true
    var_dump($x !== $z); // Outputs: boolean true
    var_dump($x < $y);   // Outputs: boolean true
    var_dump($x > $y);   // Outputs: boolean false
    var_dump($x <= $y);  // Outputs: boolean true
    var_dump($x >= $y);  // Outputs: boolean false
    ?>

    PHP Incrementing and Decrementing Operators

    The increment/decrement operators are used to increment/decrement a variable’s value.

    OperatorNameEffect
    ++$xPre-incrementIncrements $x by one, then returns $x
    $x++Post-incrementReturns $x, then increments $x by one
    --$xPre-decrementDecrements $x by one, then returns $x
    $x--Post-decrementReturns $x, then decrements $x by one

    The following example will show you these increment and decrement operators in action:

    Example

    <?php
    $x = 10;
    echo ++$x; // Outputs: 11
    echo $x;   // Outputs: 11
     
    $x = 10;
    echo $x++; // Outputs: 10
    echo $x;   // Outputs: 11
     
    $x = 10;
    echo --$x; // Outputs: 9
    echo $x;   // Outputs: 9
     
    $x = 10;
    echo $x--; // Outputs: 10
    echo $x;   // Outputs: 9
    ?>

    PHP Logical Operators

    The logical operators are typically used to combine conditional statements.

    OperatorNameExampleResult
    andAnd$x and $yTrue if both $x and $y are true
    orOr$x or $yTrue if either $x or $y is true
    xorXor$x xor $yTrue if either $x or $y is true, but not both
    &&And$x && $yTrue if both $x and $y are true
    ||Or$x || $yTrue if either $x or $y is true
    !Not!$xTrue if $x is not true

    The following example will show you these logical operators in action:

    Example

    <?php
    $year = 2014;
    // Leap years are divisible by 400 or by 4 but not 100
    if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 == 0))){
        echo "$year is a leap year.";
    } else{
        echo "$year is not a leap year.";
    }
    ?>

    PHP String Operators

    There are two operators which are specifically designed for strings.

    OperatorDescriptionExampleResult
    .Concatenation$str1 . $str2Concatenation of $str1 and $str2
    .=Concatenation assignment$str1 .= $str2Appends the $str2 to the $str1

    The following example will show you these string operators in action:

    Example

    <?php
    $x = "Hello";
    $y = " World!";
    echo $x . $y; // Outputs: Hello World!
     
    $x .= $y;
    echo $x; // Outputs: Hello World!
    ?>

    PHP Array Operators

    The array operators are used to compare arrays:

    OperatorNameExampleResult
    +Union$x + $yUnion of $x and $y
    ==Equality$x == $yTrue if $x and $y have the same key/value pairs
    ===Identity$x === $yTrue if $x and $y have the same key/value pairs in the same order and of the same types
    !=Inequality$x != $yTrue if $x is not equal to $y
    <>Inequality$x <> $yTrue if $x is not equal to $y
    !==Non-identity$x !== $yTrue if $x is not identical to $y

    The following example will show you these array operators in action:

    Example

    <?php
    $x = array("a" => "Red", "b" => "Green", "c" => "Blue");
    $y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
    $z = $x + $y; // Union of $x and $y
    var_dump($z);
    var_dump($x == $y);   // Outputs: boolean false
    var_dump($x === $y);  // Outputs: boolean false
    var_dump($x != $y);   // Outputs: boolean true
    var_dump($x <> $y);   // Outputs: boolean true
    var_dump($x !== $y);  // Outputs: boolean true
    ?>

    PHP Spaceship Operator PHP 7

    PHP 7 introduces a new spaceship operator (<=>) which can be used for comparing two expressions. It is also known as combined comparison operator.

    The spaceship operator returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater. It basically provides three-way comparison as shown in the following table:

    Operator<=> Equivalent
    $x < $y($x <=> $y) === -1
    $x <= $y($x <=> $y) === -1 || ($x <=> $y) === 0
    $x == $y($x <=> $y) === 0
    $x != $y($x <=> $y) !== 0
    $x >= $y($x <=> $y) === 1 || ($x <=> $y) === 0
    $x > $y($x <=> $y) === 1

    The following example will show you how spaceship operator actually works:

    Example

    <?php
    // Comparing Integers 
    echo 1 <=> 1; // Outputs: 0
    echo 1 <=> 2; // Outputs: -1
    echo 2 <=> 1; // Outputs: 1
     
    // Comparing Floats
    echo 1.5 <=> 1.5; // Outputs: 0
    echo 1.5 <=> 2.5; // Outputs: -1
    echo 2.5 <=> 1.5; // Outputs: 1
     
    // Comparing Strings
    echo "x" <=> "x"; // Outputs: 0
    echo "x" <=> "y"; // Outputs: -1
    echo "y" <=> "x"; // Outputs: 1
    ?>
  • PHP Strings

    What is String in PHP

    A string is a sequence of letters, numbers, special characters and arithmetic values or combination of all. The simplest way to create a string is to enclose the string literal (i.e. string characters) in single quotation marks (‘), like this:

    $my_string = ‘Hello World’;

    You can also use double quotation marks (“). However, single and double quotation marks work in different ways. Strings enclosed in single-quotes are treated almost literally, whereas the strings delimited by the double quotes replaces variables with the string representations of their values as well as specially interpreting certain escape sequences.

    The escape-sequence replacements are:

    • \n is replaced by the newline character
    • \r is replaced by the carriage-return character
    • \t is replaced by the tab character
    • \$ is replaced by the dollar sign itself ($)
    • \" is replaced by a single double-quote (")
    • \\ is replaced by a single backslash (\)

    Here’s an example to clarify the differences between single and double quoted strings:

    Example

    <?php
    $my_str = 'World';
    echo "Hello, $my_str!<br>";      // Displays: Hello World!
    echo 'Hello, $my_str!<br>';      // Displays: Hello, $my_str!
     
    echo '<pre>Hello\tWorld!</pre>'; // Displays: Hello\tWorld!
    echo "<pre>Hello\tWorld!</pre>"; // Displays: Hello   World!
    echo 'I\'ll be back';            // Displays: I'll be back
    ?>

    Manipulating PHP Strings

    PHP provides many built-in functions for manipulating strings like calculating the length of a string, find substrings or characters, replacing part of a string with different characters, take a string apart, and many others. Here are the examples of some of these functions.

    Calculating the Length of a String

    The strlen() function is used to calculate the number of characters inside a string. It also includes the blank spaces inside the string.

    Example

    <?php
    $my_str = 'Welcome to Tutorial Republic';
     
    // Outputs: 28
    echo strlen($my_str);
    ?>

    Counting Number of Words in a String

    The str_word_count() function counts the number of words in a string.

    Example

    <?php
    $my_str = 'The quick brown fox jumps over the lazy dog.';
     
    // Outputs: 9
    echo str_word_count($my_str);
    ?>

    Replacing Text within Strings

    The str_replace() replaces all occurrences of the search text within the target string.

    Example

    <?php
    $my_str = 'If the facts do not fit the theory, change the facts.';
     
    // Display replaced string
    echo str_replace("facts", "truth", $my_str);
    ?>

    The output of the above code will be:

    If the truth do not fit the theory, change the truth.

    You can optionally pass the fourth argument to the str_replace() function to know how many times the string replacements was performed, like this.

    Example

    <?php
    $my_str = 'If the facts do not fit the theory, change the facts.';
     
    // Perform string replacement
    str_replace("facts", "truth", $my_str, $count);
     
    // Display number of replacements performed
    echo "The text was replaced $count times.";
    ?>

    The output of the above code will be:

    The text was replaced 2 times.


    Reversing a String

    The strrev() function reverses a string.

    Example

    <?php
    $my_str = 'You can do anything, but not everything.';
     
    // Display reversed string
    echo strrev($my_str);
    ?>

    The output of the above code will be:

    .gnihtyreve ton tub ,gnihtyna od nac uoY

  • PHP Data Types

    Data Types in PHP

    The values assigned to a PHP variable may be of different data types including simple string and numeric types to more complex data types like arrays and objects.

    PHP supports total eight primitive data types: Integer, Floating point number or Float, String, Booleans, Array, Object, resource and NULL. These data types are used to construct variables. Now let’s discuss each one of them in detail.

    PHP Integers

    Integers are whole numbers, without a decimal point (…, -2, -1, 0, 1, 2, …). Integers can be specified in decimal (base 10), hexadecimal (base 16 – prefixed with 0x) or octal (base 8 – prefixed with 0) notation, optionally preceded by a sign (- or +).

    Example

    <?php
    $a = 123; // decimal number
    var_dump($a);
    echo "<br>";
     
    $b = -123; // a negative number
    var_dump($b);
    echo "<br>";
     
    $c = 0x1A; // hexadecimal number
    var_dump($c);
    echo "<br>";
     
    $d = 0123; // octal number
    var_dump($d);
    ?>

    Note: Since PHP 5.4+ you can also specify integers in binary (base 2) notation. To use binary notation precede the number with 0b (e.g. $var = 0b11111111;).


    PHP Strings

    Strings are sequences of characters, where every character is the same as a byte.

    A string can hold letters, numbers, and special characters and it can be as large as up to 2GB (2147483647 bytes maximum). The simplest way to specify a string is to enclose it in single quotes (e.g. ‘Hello world!’), however you can also use double quotes (“Hello world!”).

    Example

    <?php
    $a = 'Hello world!';
    echo $a;
    echo "<br>";
     
    $b = "Hello world!";
    echo $b;
    echo "<br>";
     
    $c = 'Stay here, I\'ll be back.';
    echo $c;
    ?>

    You will learn more about strings in PHP Strings tutorial.


    PHP Floating Point Numbers or Doubles

    Floating point numbers (also known as “floats”, “doubles”, or “real numbers”) are decimal or fractional numbers, like demonstrated in the example below.

    Example

    <?php
    $a = 1.234;
    var_dump($a);
    echo "<br>";
     
    $b = 10.2e3;
    var_dump($b);
    echo "<br>";
     
    $c = 4E-10;
    var_dump($c);
    ?>

    PHP Booleans

    Booleans are like a switch it has only two possible values either 1 (true) or 0 (false).

    Example

    <?php
    // Assign the value TRUE to a variable
    $show_error = true;
    var_dump($show_error);
    ?>

    PHP Arrays

    An array is a variable that can hold more than one value at a time. It is useful to aggregate a series of related items together, for example a set of country or city names.

    An array is formally defined as an indexed collection of data values. Each index (also known as the key) of an array is unique and references a corresponding value.

    Example

    <?php
    $colors = array("Red", "Green", "Blue");
    var_dump($colors);
    echo "<br>";
     
    $color_codes = array(
        "Red" => "#ff0000",
        "Green" => "#00ff00",
        "Blue" => "#0000ff"
    );
    var_dump($color_codes);
    ?>

    You will learn more about arrays in PHP Array tutorial.


    PHP Objects

    An object is a data type that not only allows storing data but also information on, how to process that data. An object is a specific instance of a class which serve as templates for objects. Objects are created based on this template via the new keyword.

    Every object has properties and methods corresponding to those of its parent class. Every object instance is completely independent, with its own properties and methods, and can thus be manipulated independently of other objects of the same class.

    Here’s a simple example of a class definition followed by the object creation.

    Example

    <?php
    // Class definition
    class greeting{
        // properties
        public $str = "Hello World!";
        
        // methods
        function show_greeting(){
            return $this->str;
        }
    }
     
    // Create object from class
    $message = new greeting;
    var_dump($message);
    ?>

    Tip: The data elements stored within an object are referred to as its properties and the information, or code which describing how to process the data is called the methods of the object.


    PHP NULL

    The special NULL value is used to represent empty variables in PHP. A variable of type NULL is a variable without any data. NULL is the only possible value of type null.

    Example

    <?php
    $a = NULL;
    var_dump($a);
    echo "<br>";
     
    $b = "Hello World!";
    $b = NULL;
    var_dump($b);
    ?>

    When a variable is created without a value in PHP like $var; it is automatically assigned a value of null. Many novice PHP developers mistakenly considered both $var1 = NULL; and $var2 = ""; are same, but this is not true. Both variables are different — the $var1 has null value while $var2 indicates no value assigned to it.


    PHP Resources

    A resource is a special variable, holding a reference to an external resource.

    Resource variables typically hold special handlers to opened files and database connections.

    Example

    <?php
    // Open a file for reading
    $handle = fopen("note.txt", "r");
    var_dump($handle);
    echo "<br>";
     
    // Connect to MySQL database server with default setting
    $link = mysqli_connect("localhost", "root", "");
    var_dump($link);
    ?>
  • PHP Echo and Print Statements

    The PHP echo Statement

    The echo statement can output one or more strings. In general terms, the echo statement can display anything that can be displayed to the browser, such as string, numbers, variables values, the results of expressions etc.

    Since echo is a language construct not actually a function (like if statement), you can use it without parentheses e.g. echo or echo(). However, if you want to pass more than one parameter to echo, the parameters must not be enclosed within parentheses.

    Display Strings of Text

    The following example will show you how to display a string of text with the echo statement:

    Example

    <?php
    // Displaying string of text
    echo "Hello World!";
    ?>

    The output of the above PHP code will look something like this:

    Hello World!

    Display HTML Code

    The following example will show you how to display HTML code using the echo statement:

    Example

    <?php
    // Displaying HTML code
    echo "<h4>This is a simple heading.</h4>";
    echo "<h4 style='color: red;'>This is heading with style.</h4>";
    ?>

    The output of the above PHP code will look something like this:

    This is a simple heading.

    This is heading with style.

    Display Variables

    The following example will show you how to display variable using the echo statement:

    Example

    <?php
    // Defining variables
    $txt = "Hello World!";
    $num = 123456789;
    $colors = array("Red", "Green", "Blue");
     
    // Displaying variables
    echo $txt;
    echo "<br>";
    echo $num;
    echo "<br>";
    echo $colors[0];
    ?>

    The output of the above PHP code will look something like this:

    Hello World!
    123456789
    Red


    The PHP print Statement

    You can also use the print statement (an alternative to echo) to display output to the browser. Like echo the print is also a language construct not a real function. So you can also use it without parentheses like: print or print().

    Both echo and print statement works exactly the same way except that the print statement can only output one string, and always returns 1. That’s why the echo statement considered marginally faster than the print statement since it doesn’t return any value.

    Display Strings of Text

    The following example will show you how to display a string of text with the print statement:

    Example

    <?php
    // Displaying string of text
    print "Hello World!";
    ?>

    The output of the above PHP code will look something like this:

    Hello World!

    Display HTML Code

    The following example will show you how to display HTML code using the print statement:

    Example

    <?php
    // Displaying HTML code
    print "<h4>This is a simple heading.</h4>";
    print "<h4 style='color: red;'>This is heading with style.</h4>";
    ?>

    The output of the above PHP code will look something like this:

    This is a simple heading.

    This is heading with style.

    Display Variables

    The following example will show you how to display variable using the print statement:

    Example

    <?php
    // Defining variables
    $txt = "Hello World!";
    $num = 123456789;
    $colors = array("Red", "Green", "Blue");
     
    // Displaying variables
    print $txt;
    print "<br>";
    print $num;
    print "<br>";
    print $colors[0];
    ?>

    The output of the above PHP code will look something like this:

    Hello World!
    123456789
    Red

  • PHP Constants

    What is Constant in PHP

    A constant is a name or an identifier for a fixed value. Constant are like variables, except that once they are defined, they cannot be undefined or changed (except magic constants).

    Constants are very useful for storing data that doesn’t change while the script is running. Common examples of such data include configuration settings such as database username and password, website’s base URL, company name, etc.

    Constants are defined using PHP’s define() function, which accepts two arguments: the name of the constant, and its value. Once defined the constant value can be accessed at any time just by referring to its name. Here is a simple example:

    Example

    <?php
    // Defining constant
    define("SITE_URL", "https://www.tutorialrepublic.com/");
     
    // Using constant
    echo 'Thank you for visiting - ' . SITE_URL;
    ?>

    The output of the above code will be:

    The PHP echo statement is often used to display or output data to the web browser. We will learn more about this statement in the next chapter.

    Tip: By storing the value in a constant instead of a variable, you can make sure that the value won’t get changed accidentally when your application runs.


    Naming Conventions for PHP Constants

    Name of constants must follow the same rules as variable names, which means a valid constant name must starts with a letter or underscore, followed by any number of letters, numbers or underscores with one exception: the $ prefix is not required for constant names.