Introduction

The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side scripting language designed specifically for web development. It is open-source which means it is free to download and use. It is very simple to learn and use. The files have the extension “.php”.

Rasmus Lerdorf inspired the first version of PHP and participating in the later versions. It is an interpreted language and it does not require a compiler.

What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. You can even configure your web server to process all your HTML files with PHP, and then there's really no way that users can tell what you have up your sleeve.

What can PHP do

There are three main areas where PHP scripts are used.

  • Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work: the PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming.

  • Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks.

  • Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution.

Why should we use PHP

PHP can actually do anything related to server-side scripting or more popularly known as the backend of a website. For example, PHP can receive data from forms, generate dynamic page content, can work with databases, create sessions, send and receive cookies, send emails etc. There are also many hash functions available in PHP to encrypt user's data that makes PHP secure and reliable to be used as a server-side scripting language. So these are some of the abilities of PHP that makes it suitable to be used as server-side scripting language.

Even if you are not convinced by the above abilities of PHP, there are some more features of PHP. PHP can run on all major operating systems like Windows, Linux, Unix, Mac OS X etc. Almost all of the major servers available today like Apache supports PHP. PHP allows using wide range of databases. And the most important factor is that it is free to use and download and anyone can download PHP from its official source : www.php.net.

Basic syntax

The structure which defines PHP computer language is called PHP syntax.

The PHP script is executed on the server and the HTML result is sent to the browser. It can normally have HTML and PHP tags. PHP or Hypertext Preprocessor is a widely used open-source general-purpose scripting language and can be embedded with HTML. PHP files are saved with the “.php” extension. PHP scripts can be written anywhere in the document within PHP tags along with normal HTML.

Writing the PHP code inside "<?php ... ?>" is called Escaping to PHP.

The mechanism of separating a normal HTML from PHP code is called the mechanism of Escaping To PHP. There are various ways in which this can be done. Few methods are already set by default but in order to use few others like Short-open or ASP-style tags, we need to change the configuration of the php.ini file. These tags are also used for embedding PHP within HTML. There are 4 such tags available for this purpose.

Let's look at the hello world program in PHP.

<?php echo "Hello World"; ?>

The above program will be outputting "Hello World" string.

Constants

Constants can be defined using the define() function.

Here is an example.

<?php define('APP_VERSION', 1.1.1); ?>

The define() function accepts 2 parameter. The first one is the constant name, and the second one is the value of the constant.

Comments

Comments help in reminding the developer about the code if it's re-visited after a period of time.

A comment is something that is ignored and not read or executed by the PHP engine or the language as part of a program and is written to make the code more readable and understandable. These are used to help other users and developers to describe the code and what it is trying to do. It can also be used in documenting a set of codes or parts of a program. You must have noticed this in the above sample programs.

PHP supports two types of comment:

Variables

Variables in a program are used to store some values or data that can be used later in a program. The variables are also like containers that store character values, numeric values, memory addresses, and strings. PHP has its own way of declaring and storing variables.

There are few rules, that needs to be followed and facts that need to be kept in mind while dealing with variables in PHP:

Data types

Data Types define the type of data a variable can store. PHP allows eight different types of data types. All of them are discussed below. There are pre-defined, user-defined, and special data types.

The predefined data types are:

The user-defined (compound) data types are:

The special data types are:

The first five are called simple data types and the last three are compound data types:

  1. Integer : Integers hold only whole numbers including positive and negative numbers, i.e., numbers without fractional part or decimal point. They can be decimal (base 10), octal (base 8), or hexadecimal (base 16). The default base is decimal (base 10). The octal integers can be declared with leading 0 and the hexadecimal can be declared with leading 0x. The range of integers must lie between -2^31 to 2^31.

    <?php // decimal base integers $decimal = 50; // octal base integers $octal = 07; // hexadecimal base integers $hexadecimal = 0x45; ?>
  2. Double: Can hold numbers containing fractional or decimal parts including positive and negative numbers or a number in exponential form. By default, the variables add a minimum number of decimal places. The Double data type is the same as a float as floating-point numbers or real numbers.

    <?php $val1 = 50.85; $val2 = 654.26; ?>
  3. String: Hold letters or any alphabets, even numbers are included. These are written within double quotes during declaration. The strings can also be written within single quotes, but they will be treated differently while printing variables. To clarify this look at the example below.

    <?php $name = "Aydin"; ?>
  4. NULL: These are special types of variables that can hold only one value i.e., NULL. We follow the convention of writing it in capital form, but it’s case-sensitive. If a variable is created without a value or no value, it is automatically assigned a value of NULL. It is written in capital letters.

    <?php $nm = NULL; echo $nm; // This will give no output ?>
  5. Boolean: Boolean data types are used in conditional testing. Hold only two values, either TRUE(1) or FALSE(0). Successful events will return true and unsuccessful events return false. NULL type values are also treated as false in Boolean. Apart from NULL, 0 is also considered false in boolean. If a string is empty then it is also considered false in boolean data type.

  6. Arrays: Array is a compound data-type that can store multiple values of the same data type. Below is an example of an array of integers. It combines series of data that are related together.

    <?php $intArray = array( 10, 20 , 30); echo "First Element: $intArray[0]\n"; echo "Second Element: $intArray[1]\n"; echo "Third Element: $intArray[2]\n"; ?>
  7. Objects: Objects are defined as instances of user-defined classes that can hold both values and functions and information for data processing specific to the class. This is an advanced topic and will be discussed in detail in further articles. When the objects are created, they inherit all the properties and behaviors from the class, having different values for all the properties. Objects are explicitly declared and created from the new keyword.

  8. Resources: Resources in PHP are not an exact data type. These are basically used to store references to some function call or to external PHP resources. For example, consider a database call. This is an external resource. Resource variables hold special handles to files and database connections. We will discuss resources in detail in further articles.

if statement

This statement allows us to set a condition. On being TRUE, the following block of code enclosed within the if clause will be executed.

<?php $x = 12; if ($x > 0) { echo "The number is positive"; } ?>
if else statement

We understood that if a condition will hold i.e., TRUE, then the block of code within if will be executed. But what if the condition is not TRUE and we want to perform an action? This is where else comes into play. If a condition is TRUE then if block gets executed, otherwise else block gets executed.

<?php $x = -12; if ($x > 0) { echo "The number is positive"; } else { echo "The number is negative"; } ?>

The output will be "The number is negative".

if elseif else statement

We understood that if a condition will hold i.e., TRUE, then the block of code within if will be executed. But what if the condition is not TRUE and we want to perform an action? This is where else comes into play. If a condition is TRUE then if block gets executed, otherwise else block gets executed.

<?php $x = "August"; if ($x == "January") { echo "Happy Republic Day"; } elseif ($x == "August") { echo "Happy Independence Day!!!"; } else { echo "Nothing to show"; } ?>

The output will be "Happy Independence Day!!!".

switch statement

The "switch" performs in various cases i.e., it has various cases to which it matches the condition and appropriately executes a particular case block. It first evaluates an expression and then compares with the values of each case. If a case matches then the same case is executed. To use switch, we need to get familiar with two different keywords namely, break and default.

  1. The break statement is used to stop the automatic control flow into the next cases and exit from the switch case.

  2. The default statement contains the code that would execute if none of the cases match.

<?php $n = "February"; switch($n) { case "January": echo "Its January"; break; case "February": echo "Its February"; break; case "March": echo "Its March"; break; default: echo "Doesn't exist"; } ?>

The output will be "Its February".

for loop

This type of loops is used when the user knows in advance, how many times the block needs to execute. That is, the number of iterations is known beforehand. These type of loops are also known as entry-controlled loops. There are three main parameters to the code, namely the initialization, the test condition and the counter.

  1. Initialization Expression: In this expression we have to initialize the loop counter to some value. for example: $num = 1;

  2. Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of loop and go to update expression otherwise we will exit from the for loop. For example: $num <= 10;

  3. Update Expression: After executing loop body this expression increments/decrements the loop variable by some value. for example: $num += 2;

<?php for ($num = 1; $num <= 10; $num += 2) { echo "$num \n"; } ?>

The output will be:

                1
                3
                5
                7
                9
            
while loop

The while loop is also an entry control loop like for loops i.e., it first checks the condition at the start of the loop and if its true then it enters the loop and executes the block of statements, and goes on executing it as long as the condition holds true.

<?php $num = 2; while ($num < 12) { $num += 2; echo $num, "\n"; } ?>

The output will be:

                4
                6
                8
                10
                12
            
do while loop

This is an exit control loop which means that it first enters the loop, executes the statements, and then checks the condition. Therefore, a statement is executed at least once on using the do…while loop. After executing once, the program is executed as long as the condition holds true.

<?php $num = 2; do { $num += 2; echo $num, "\n"; } while ($num < 12); ?>

The output will be:

                4
                6
                8
                10
                12
            
foreach loop

This loop is used to iterate over arrays. For every counter of loop, an array element is assigned and the next counter is shifted to the next element.

<?php $arr = array (10, 20, 30, 40, 50, 60); foreach ($arr as $val) { echo "$val \n"; } $arr = array ("Ram", "Laxman", "Sita"); foreach ($arr as $key => $val) { echo "$key: $val \n"; } ?>

The output will be:

                10 
                20 
                30 
                40 
                50 
                60 
                0: Ram 
                1: Laxman 
                2: Sita