Blog

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

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

  • PHP Variables

    What is Variable in PHP

    Variables are used to store data, like string of text, numbers, etc. Variable values can change over the course of a script. Here’re some important things to know about variables:

    • In PHP, a variable does not need to be declared before adding a value to it. PHP automatically converts the variable to the correct data type, depending on its value.
    • After declaring a variable it can be reused throughout the code.
    • The assignment operator (=) used to assign value to a variable.

    In PHP variable can be declared as: $var_name = value;

    Example

    <?php
    // Declaring variables
    $txt = "Hello World!";
    $number = 10;
     
    // Displaying variables value
    echo $txt;  // Output: Hello World!
    echo $number; // Output: 10
    ?>

    In the above example we have created two variables where first one has assigned with a string value and the second has assigned with a number. Later we’ve displayed the variables values in the browser using the echo statement. The PHP echo statement is often used to output data to the browser. We will learn more about this in upcoming chapter.

    Naming Conventions for PHP Variables

    These are the following rules for naming a PHP variable:

    • All variables in PHP start with a $ sign, followed by the name of the variable.
    • A variable name must start with a letter or the underscore character _.
    • A variable name cannot start with a number.
    • A variable name in PHP can only contain alpha-numeric characters and    underscores (A-z0-9, and _).
    • A variable name cannot contain spaces.
  • PHP Syntax

    Standard PHP Syntax

    A PHP script starts with the <?php and ends with the ?> tag.

    The PHP delimiter <?php and ?> in the following example simply tells the PHP engine to treat the enclosed code block as PHP code, rather than simple HTML.

    Example

    <?php
    // Some code to be executed
    echo "Hello, world!";
    ?>

    Every PHP statement end with a semicolon (;) — this tells the PHP engine that the end of the current statement has been reached.


    Embedding PHP within HTML

    PHP files are plain text files with .php extension. Inside a PHP file you can write HTML like you do in regular HTML pages as well as embed PHP codes for server side execution.

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>A Simple PHP File</title>
    </head>
    <body>
        <h1><?php echo "Hello, world!"; ?></h1>
    </body>
    </html>

    The above example shows how you can embed PHP codes within HTML to create well-formed dynamic web pages. If you view the source code of the resulting web page in your browser, the only difference you will see is the PHP code <?php echo "Hello, world!"; ?> has been replaced with the output “Hello, world!”.

    What happend here is? when you run this code the PHP engine exacuted the instructions between the <?php … ?> tags and leave rest of the thing as it is. At the end the web server send the final output back to your browser which is completely in HTML.


    PHP Comments

    A comment is simply text that is ignored by the PHP engine. The purpose of comments is to make the code more readable. It may help other developer (or you in the future when you edit the source code) to understand what you were trying to do with the PHP.

    PHP support single-line as well as multi-line comments. To write a single-line comment either start the line with either two slashes (//) or a hash symbol (#). For example:

    Example

    <?php
    // This is a single line comment
    # This is also a single line comment
    echo "Hello, world!";
    ?>

    However to write multi-line comments, start the comment with a slash followed by an asterisk (/*) and end the comment with an asterisk followed by a slash (*/), like this:

    Example

    <?php
    /*
    This is a multiple line comment block
    that spans across more than
    one line
    */
    echo "Hello, world!";
    ?>

    Case Sensitivity in PHP

    Variable names in PHP are case-sensitive. As a result the variables $color$Color and $COLOR are treated as three different variables.

    Example

    <?php
    // Assign value to variable
    $color = "blue";
     
    // Try to print variable value
    echo "The color of the sky is " . $color . "<br>";
    echo "The color of the sky is " . $Color . "<br>";
    echo "The color of the sky is " . $COLOR . "<br>";
    ?>

    If you try to run the above example code it will only display the value of the variable $color and produce the “Undefined variable” warning for the variable $Color and $COLOR.

    However the keywords, function and classes names are case-insensitive. As a result calling the gettype() or GETTYPE() produce the same result.

    Example

    <?php
    // Assign value to variable
    $color = "blue";
     
    // Get the type of a variable
    echo gettype($color) . "<br>";
    echo GETTYPE($color) . "<br>";
    ?>

    If you try to run the above example code both the functions gettype() and GETTYPE() gives the same output, which is: string.

  • PHP Getting Started

    Getting Started with PHP

    Here, you will learn how easy it is to create dynamic web pages using PHP. Before begin, be sure to have a code editor and some working knowledge of HTML and CSS.

    If you’re just starting out in web development, start learning from here »

    Well, let’s get straight into it.

    Setting Up a Local Web Server

    PHP script execute on a web server running PHP. So before you start writing any PHP program you need the following program installed on your computer.

    • The Apache Web server
    • The PHP engine
    • The MySQL database server

    You can either install them individually or choose a pre-configured package for your operating system like Linux and Windows. Popular pre-configured package are XAMPP and WampServer.

    WampServer is a Windows web development environment. It allows you to create web applications with Apache2, PHP and a MySQL database. It will also provide the MySQL administrative tool PhpMyAdmin to easily manage your databases using a web browser.

    The official website for downloading and installation instructions for the WampServer: http://www.wampserver.com/en/


    Creating Your First PHP Script

    Now that you have successfully installed WampServer on your computer. In this section we will create a very simple PHP script that displays the text “Hello, world!” in the browser window.

    Ok, click on the WampServer icon somewhere on your Windows task bar and select the “www directory”. Alternatively, you can access the “www” directory through navigating the C:\wamp\www. Create a subdirectory in “www” directory let’s say “project”.

    Now open up your favorite code editor and create a new PHP file then type the following code:

    Example

    <?php
    // Display greeting message
    echo "Hello, world!";
    ?>

    Now save this file as “hello.php” in your project folder (located at C:\wamp\www\project), and view the result in your browser through visiting this URL: http://localhost/project/hello.php.

    Alternatively, you can access the “hello.php” file through selecting the localhost option and then select the project folder from the WampSever menu on the taskbar.

    PHP can be embedded within a normal HTML web page. That means inside your HTML document you can write the PHP statements, as demonstrated in the follwoing example:

    Example

    <!DOCTYPE HTML>
    <html>
    <head>
        <title>PHP Application</title>
    </head>
    <body>
    <?php
    // Display greeting message
    echo 'Hello World!';
    ?>
    </body>
    </html>

    You will learn what each of these statements means in upcoming chapters.