PHP Basics

1. First PHP Program

This is your first programming code in PHP. As a learner you can write simple program by displaying hello world or some other text in browser. Before doing this, you need to have PHP & MySQL Environment installed in your computer or at least you need to have access to webserver.

First we will start this by opening PHP opening tags. For PHP server to process php file, that file should end with .php extension & it should have PHP opening tag. Below is the code to open PHP tag.


<?php

Then to simply print any text in PHP, you need to use echo PHP function. When using echo PHP function, after echo function text should be places in single quotes or double quotes. Only use one pattern throughout your codes.

After closing quotation mark, there should be a semicolon. If you are not placing semicolon, you can’t open new statement in your PHP file.


echo "Hello World";

echo "Hello World";

After completing echo statement, then close the PHP tag by using below tag


?>


And your complete program would look like this below code.

<?php
echo "Hello World";
?>

Congrats, now you have completed your first programming code.

2. Introduction to Variables in PHP

Variables have important significance in PHP programs, For storing any kind of data we will be using variables. In database driven applications, these variables will be used. Variables are defined with dollar symbol in front of the variable.

In variables, there won’t be any spaces. This is important to remember. Don’t use hyphens and underscores in variables.

You can use camel case letters to identify another word in variables.

For example, if you want to create a variable with the name of my variable. Please go through below statements to understand best ways to define variables.

$myvariable

$MyVariable

Wrong statements to define variables

$my variable

$my-variable

$my_variable

If you have multi-word terms use Camel case lettered variables.

We can store any kind of data in variables. Like we can store Lines of text in a variable, this (Lines of text) is called in any programming language as strings. We can store Numbers, this is called as integers. We can store numbers with decimal points, this is called as float in PHP technical terms

Now you have clear understanding of what are variables & how you can use them and the best way’s to write variable in your programs.

3. Using Variables in PHP

Using Variables, variables are important in PHP programs. We can store line of text in variables, this is called as strings in PHP. We can store numbers, this is called as integers. We can store number with decimal values, this is called as float.

First we will start with storing text data in variable. To store data simply create a php file, and start with opening php tag.

For more information access this page.

After that define the variable, and put equals to symbol. What ever you want to store, put that text in quotation marks. Either that can be single quotes or double quotes.

To end that statement use semicolon after closing quotation mark. By doing this, you can create a new statement right after the old statement.


$myvar = "This is simple text";

This above method is for storing data in strings. For storing numbers also it’s same but we don’t use quotation marks around the value. We can use this variable to output the value.


$x = 5;

And after the above statement you can write new statement, because we are closing it with semicolon.

Next thing is to store number with decimal point, this is called as float. This can be done same way as the above.


$y = 5.5;

We can use this integer and float to do the mathematical calculations.

To know more about calculations read here.

4. Super Global Variables in PHP

Super Global Variables in PHP are predefined varialbes in php, they can be accessed from any scope. They can be accessed from classes, functions. These below are the Super Global Variables in PHP.

  • $GLOBALS
  • $_SERVER
  • $_GET
  • $_POST
  • $_FILES
  • $_COOKIE
  • $_SESSION
  • $_REQUEST
  • $_ENV
  • 5. Understanding Data Types in PHP

    Understanding Data Types in PHP, there are different types of data types in PHP. Previously we have discussed three types of data types in variables.

    These are the available data types in PHP

    • String
    • Integer
    • Float
    • Boolean
    • Array​​​​
    • Object
    • NULL
    • Resource

    String : It’s a plain text that we can store in variables. String is a text that is inside quotes, either that may be single quotes or double quotes. Please see below example.


    $var = "This is simple text";

    Integer : Integer is simply defined as number without decimal numbers. Integer data can be inbetween -2,147,483,648 and 2,147,483,647.

    Simple example of Integer :


    $x = 5;

    Float : Float is same as number but with decimal point.
    Below is an example of float :


    $y = 5.805;

    Boolean : Boolean Data types are used in conditionnal statements. Boolean value contains two values either TRUE or FALSE.

    Example of using Boolean :


    $x = TRUE;

    $y = FALSE;

    Array : Array’s are used to store multiple values in single variable. These arrays are used in retrieving data from database.

    Simple example of Array :


    $colors =  array(red, green, blue, yellow, orange);

    Like this above example, arrays are used to store lot of data.

    Object : Object are used to store data. But these objects are used in Object Oriented Programming. It is advanced topic, as a beginner we will explore this topic later.

    NULL : If a variable is created without any value or data, then the value of that variable is NULL datatype.

    Simple Example of NULL datatype :


    $x = NULL;

    Resource : T

    6. Using Operators in PHP

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Increment/Decrement operators
  • Logical operators
  • String operators
  • Array operators
  • Arithmetic Operators in PHP

    Operator

    Name

    Example

    Result

    +

    Addition

    $x + $y

    Sum of $x and $y

    -

    Subtraction

    $x - $y

    Difference of $x and $y

    *

    Multiplication

    $x * $y

    Product of $x and $y

    /

    Division

    $x / $y

    Quotient of $x and $y

    %

    Modulus

    $x % $y

    Remainder of $x divided by $y

    **

    Exponentiation

    $x ** $y

    Result of raising $x to the $y'th power 

    Assignment operators

    Assignment

    Same as

    Description

    x = y

    x = y

    The left operand gets set to the value of the expression on the right

    x += y

    x = x + y

    Addition

    x -= y

    x = x + y

    Subtraction

    x *= y

    x = x * y

    Multiplication

    x /= y

    x = x / y

    Division

    x %= y

    x = x % y

    Modulus

    7. Writing Statements and Comments in PHP

    Writing Statements and Comments in PHP, you know how to write statements in PHP. Now we will see how we can use comments in statements. PHP Comments are similar to comments that we use in HTML, the only difference is the comment syntax in PHP.

    There are two types of comments in PHP, one is single line comments and other one is multi-line comments.

    PHP Single Line Comments

    We can write single line comments in PHP with two forward slashes. We can write as long as comments but without taking line break. If we take the line break, it will be considered as new line. So, we need to add new comments tag.

    For Single Line Comments, we don’t need to close the comment. But for multi-line comments we should close it.

    PHP Multi-Line Comments

    Multi-Line Comments, we can write them starting with syntax of forward slash followed by star (/*). Same way we can close the multi line comments opposite way star followed by forward slash.

    In multi line comments you can write n number of lines. Closing the comment is a must other everything after opening comment is considered as complete comment.

    8. Conditional Statements in PHP

    Conditional Statements in PHP are used to check the conditions between two statements, if the condition is true then given statement will be executed. Otherwise, the next statement will be executed.

    Syntax of if statement
    If the condition is true, then the below statement will be executed.


    if(condition){
    Statements to be executed
    }

    Example code for if statement

    Here, we have assigned $a as value 5. And checking that if $a value is greater than two or not. Because the statement is true, following statement will be executed.

    $a = 5;
    if($a > 2){
    echo "a number is greater than 2";
    }

    Syntax of if… else… statement

    if(condition){
    These Statements will be executed, if the condition is true
    }else{
    These statements will be executed, if the condition is false
    }

    Example code for if… else statement
    Here in this example, a variable is assigned as value 5. In first condition we are checking that if a is less than 2, which is obviously wrong. So, that next statement will be executed.

    $a = 5;
    if($a < 2){
    echo "a number is less than 2";
    }else{
    echo "a number is greater than 2";
    }

    Syntax of if… elseif statement

    if(condition){
    Statements to be executed if the above condition is true
    }elseif(condition...1){
    Statements to be executed if the above condition is true
    }elseif(.....){
    .
    .
    .
    }

    Example code for if… elseif statement
    Here in this example, we assigned a variable value of 5. In the first condition we are checking that is variable a is equal to 3 or not, which is false. In the second condition we are checking that is variable a is equal to 4 or not, which is also false. In the third condition we are checking that the variable is equal to 5, which is true. So, here executes the statements and exits. If this condition is also false, it continues to the next condition. We can continue for n number of conditions.

    $a = 5;
    if($a == 3){
    echo "a value is equal to 3";
    }elseif($a == 4){
    echo "a number is equal to 4";
    }elseif($a == 5){
    echo "a number is equal to 5";
    }elseif($a == 6){
    echo "a number is equal to 6";
    }

    9. Switch() Statement in PHP

    Switch() Statement in PHP, Switch Statements are used to execute different cases based on the condition. In switch statement we can write n number of cases. If nothing works we always have an option to execute default condition.

    Sytax of Switch() Statement in PHP

    switch (a) {
    case label1:
    code to be executed if a=label1;
    break;
    case label2:
    code to be executed if a=label2;
    break;
    case label3:
    code to be executed if a=label3;
    break;
    ...
    default:
    code to be executed if a is different from all labels;
    }

    Example code for Switch() Statement in PHP
    Here, in this below code. A variable is defined with color value. In the switch statement each case, statement checks the variable value with case value. If both matches, following statements will be executed. break statement is used to break out of the switch, if the condition meets.

    $color = "red";
    switch ($color) {
    case "red":
    echo "Your favorite color is red!";
    break;
    case "blue":
    echo "Your favorite color is blue!";
    break;
    case "green":
    echo "Your favorite color is green!";
    break;
    default:
    echo "Your favorite color is neither red, blue, nor green!";
    }

    10. for() Loop in PHP

    for() Loop in PHP, for loop executes the code inside the block for specified number of times.

    Syntax of for() Loop in PHP

    for (init counter; test counter; increment counter) {
    code to be executed;
    }

    Example code of for() Loop in PHP
    Here in this example, we are intiating variable i as 1, condition to check is if variable i is less than or equal to 10. And increment i till the condition fails.

    If i = 1, i is less than 10, Value to be displayed is 1. then var i value increments by one.
    If i = 2, i is less than 10, Value to be displayed is 2. then var i value increments by one.
    If i = 3, i is less than 10, Value to be displayed is 3. then var i value increments by one.
    If i = 4, i is less than 10, Value to be displayed is 4. then var i value increments by one.
    If i = 5, i is less than 10, Value to be displayed is 5. then var i value increments by one.
    If i = 6, i is less than 10, Value to be displayed is 6. then var i value increments by one.
    If i = 7, i is less than 10, Value to be displayed is 7. then var i value increments by one.
    If i = 8, i is less than 10, Value to be displayed is 8. then var i value increments by one.
    If i = 9, i is less than 10, Value to be displayed is 9. then var i value increments by one.
    If i = 10, i is equal to 10, Value to be displayed is 10. then var i value increments by one.
    If i = 11, i is not equal to 10 and not less than 10, here for loop breaks out. And continue to execute next block of code after for loop.

    for ($i = 1; $i <= 10; $i++) { echo $i; }

    11. While() Loop in PHP

    While() Loop in PHP, While Loop executes specific block of code if the condition is true.

    Syntax of While() Loop in PHP

    while (expr){
    statement
    }

    Example code of While() Loop in PHP

    $i = 1;
    while ($i <= 10) { echo "The number is: $i 
    “;
    echo $i++;
    }

    12. do while() Loop in PHP

    do while() Loop in PHP, do while loops are same as while loops except executes the code once. Then checks the condition & repeats the loop.

    Syntax of do while() Loop in PHP

    do {
    code to be executed;
    } while (condition is true);

    Example code of do while() Loop in PHP
    Here in this example code, we are assigning variable x as 1. Then do while loop will executes the statement after that increments variable x and then checks the condition.

    x = 1, displays 1, then increments to 2, still 2 is less than 5
    Now x = 2, displays 2, then increments to 3, still 3 is less than 5
    Now x = 3, displays 3, then increments to 4, still 4 is less than 5
    Now x = 4, displays 4, then increments to 5, still 5 is equal to 5
    Now x = 5, displays 5, then increments to 6, but now 6 is less than or equal to 5. do while loops exits here
    $x = 1;

    do {
    echo “The number is: $x 
    “;
    $x++;
    } while ($x <= 5);

    13. foreach() Loop in PHP

    foreach() Loop in PHP, foreach loops are used to assigns an array pocket value into variables until it reaches last array element.

    Syntax of foreach() Loop in PHP

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

    Example code of foreach() Loop in PHP
    Here in this example code, colors is an array with 4 color values. In foreach loop, loops through each value in colors array and assigns it to variable value. And then outputs the variable value. colors array looped through each element till it reaches last array element.

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

    14. Arrays in PHP

    Arrays in PHP are used to store multiple values inside an array. There are three types of arrays.

  • Indexed arrays – Arrays with a numeric index
  • Associative arrays – Arrays with named keys
  • Multidimensional arrays – Arrays containing one or more arrays
  • Syntax of an array
    In this syntax, we are just adding the values to array. There are no pocket numbers, but they can be accessed from zero, one, two, three and so on… First value is always assigned to pocket values zero. These are called as Indexed arrays.

    array(value, value2, value3, … )

    In this syntax, we are adding values to array with accessible key. We can always access exact value with key name or number, whatever we assign to it. These are called as Associative arrays.

    array(
    key => value,
    key2 => value2,
    key3 => value3,

    )

    Example code of an array

    This is an example code for Indexed array. In this type of array, we will just add values to cars array. And then we can access them based on the pocket numbers. Array pocket number start from zero.

    $cars = array(“Volvo”, “BMW”, “Toyota”);
    echo “I like ” . $cars[0] . “, ” . $cars[1] . ” and ” . $cars[2] . “.”;

    This is an example code for Associative array. In this type of array, we will add pocket key and value. And whenever we want to access them, we can do it by based on the array key. Array key is name of the person and the array value is age of that person.

    $age = array(“Peter”=>”35”, “Ben”=>”37”, “Joe”=>”43”);

    foreach($age as $x => $x_value) {
    echo “Key=” . $x . “, Value=” . $x_value;
    echo “
    “;
    }