PHP

What is PHP



Whenever anyone is learning PHP, the most common questions that first come up are: What is PHP? And how does it work?
It is precisely these questions we will look at in this lesson. It's a big help to understand such basics related to PHP before you start developing you own PHP pages. Such basic understanding will increase the speed of learning significantly.
So, let's get started!

What You Should Already Know

Before you continue you should have a basic understanding of the following:
  • HTML
  • JavaScript

What is PHP?

  • PHP stands for PHP: Hypertext Preprocessor
  • PHP is a widely-used, open source scripting language
  • PHP scripts are executed on the server
  • PHP is free to download and use
PHP was originally an acronym for Personal Home Pages, but is now a recursive acronym for PHP: Hypertext Preprocessor.
PHP was originally developed by the Danish Greenlander Rasmus Lerdorf, and was subsequently developed as open source. PHP is not a proper web standard – but an open-source technology. PHP is neither real programming language – but PHP lets you use so-called scripting in your documents.
To describe what a PHP page is, you could say that it is a file with the extension . php that contains a combination of HTML tags and scripts that run on a web server.

What is a PHP File?

  • PHP files can contain text, HTML, JavaScript code, and PHP code
  • PHP code are executed on the server, and the result is returned to the browser as plain HTML
  • PHP files have a default file extension of ".php"

What Can PHP Do?

  • PHP can generate dynamic page content
  • PHP can create, open, read, write, and close files on the server
  • PHP can collect form data
  • PHP can send and receive cookies
  • PHP can add, delete, modify data in your database
  • PHP can restrict users to access some pages on your website
  • PHP can encrypt data
With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies. You can also output any text, such as XHTML and XML.

Why PHP?

  • PHP runs on different platforms (Windows, Linux, Unix, Mac OS X, etc.)
  • PHP is compatible with almost all servers used today (Apache, IIS, etc.)
  • PHP has support for a wide range of databases
  • PHP is free. Download it from the official PHP resource: www.php.net
  • PHP is easy to learn and runs efficiently on the server side

How does PHP work?

The best way to explain how PHP works is by comparing it with standard HTML. Imagine you type the address of an HTML document (e.g. http://www.mysite.com/page.htm) in the address line of the browser. This way you request an HTML page. It could be illustrated like this:
php tutorial
As you can see, the server simply sends an HTML file to the client. But if you instead typehttp://www.mysite.com/page.php – and thus request an PHP page – the server is put to work:
php tutorial 02
The server first reads the PHP file carefully to see if there are any tasks that need to be executed. Only when the server has done what it is supposed to do, the result is then sent to the client. It is important to understand that the client only sees the result of the server's work, not the actual instructions.
This means that if you click "view source" on a PHP page, you do not see the PHP codes – only basic HTML tags. Therefore, you cannot see how a PHP page is made by using "view source". You have to learn PHP in other ways, for example, by reading this tutorial.
What you learn in this tutorial is to write commands to a server!
So, the first thing you need to get ahold of is… a server! But don't worry – you don't need to buy a new computer. You just need to install some software on your computer that makes it function as a server. Another option is to have a website on a hosted server that supports PHP. Then you just need to be online while coding.

PHP Installation

What Do I Need for PHP Installation ?

PHP is a server-side technology. Therefore, you need to have a server to run PHP. But it doesn't need to cost you anything to make this upgrade and there are several options for doing so.
Since you ultimately only need to choose one option, this lesson is divided into three parts. First comes a little introduction on the different options (just choose the one that suits you best). When your server is up and running, we'll pick up with Lesson 3 to make your first PHP page.
To start using PHP, you can:
  • Find a web host with PHP and MySQL support
  • Install a web server on your own PC, and then install PHP and MySQL

Use a Web Host With PHP Support

If your server has activated support for PHP you do not need to do anything.
Just create some .php files, place them in your web directory, and the server will automatically parse them for you.
You do not need to compile anything or install any extra tools.
Because PHP is free, most web hosts offer PHP support.

Install PHP on your computer

It's no walk in the park to install PHP on your computer. This option is only recommend for experienced computer users, but it can obviously be done. Here are links to downloads and installtion guides:

Option 3: XAMPP

XAMPP is a program that makes it easy and possible for us ordinary folks to run the PHP directly on our computer without having to install PHP on our own.

PHP Syntax

The PHP script is executed on the server, and the plain HTML result is sent back to the browser.

Basic PHP Syntax

A PHP script can be placed anywhere in the document.
A PHP script starts with  and ends with ?>:
// PHP code goes here
?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that sends the text "Hello World!" back to the browser:

Example



My first PHP page

echo "Hello World!";
?>
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another.
With PHP, there are two basic statements to output text in the browser: echo and print.

Comments in PHP

Commenting PHP Code:

Comments in php, A comment is the portion of a program that exists only for the human reader and stripped out before displaying the programs result. There are two commenting formats in PHP:
Single-line comments: They are generally used for short explanations or notes relevant to the local code. Here are the examples of single line comments.
# This is a comment, and
# This is the second line of the comment
// This is a comment too. Each style comments only
print "An example with single line comments";
?>

PHP Variables

The main way to store information in the middle of a PHP program is by using a variable. Think of variables as containers for storing data.

Much Like Algebra

x=5
y=6
z=x+y
In algebra we use letters (like x) to hold values (like 5).
From the expression z=x+y above, we can calculate the value of z to be 11.
In PHP these letters are called variables.

PHP Variables

As with algebra, PHP variables can be used to hold values (x=5) or expressions (z=x+y).
Variable can have short names (like x and y) or more descriptive names (age, carname, totalvolume).
Here are the most important things to know about variables in PHP.
  • All variables in PHP are denoted with a leading dollar sign ($).
  • The value of a variable is the value of its most recent assignment.
  • Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.
  • Variables can, but do not need, to be declared before assignment.
  • Variables in PHP do not have intrinsic types – a variable does not know in advance whether it will be used to store a number or a string of characters.
  • Variables used before they are assigned have default values.
  • PHP does a good job of automatically converting types from one to another when necessary.
  • PHP variables are Perl-like.

Creating (Declaring) PHP Variables

PHP has no command for declaring a variable.
A variable is created the moment you first assign a value to it:
$txt="Hello world!";
$x=5;
After the execution of the statements above, the variable txt will hold the value Hello world!, and the variable x will hold the value 5.
Note: When you assign a text value to a variable, put quotes around the value.

PHP Variable Types:

PHP has a total of eight data types which we use to construct our variables:
  • Integers: are whole numbers, without a decimal point, like 4195.
  • Doubles: are floating-point numbers, like 3.14159 or 49.1.
  • Booleans: have only two possible values either true or false.
  • NULL: is a special type that only has one value: NULL.
  • Strings: are sequences of characters, like 'PHP supports string operations.'
  • Arrays: are named and indexed collections of other values.
  • Objects: are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
  • Resources: are special variables that hold references to resources external to PHP (such as database connections).
The first five are simple types, and the next two (arrays and objects) are compound – the compound types can package up other arbitrary values of arbitrary type, whereas the simple types cannot.
We will explain only simile data type in this chapters. Array and Objects will be explained separately.

Integers:

They are whole numbers, without a decimal point, like 4195. They are the simplest type .they correspond to simple whole numbers, both positive and negative. Integers can be assigned to variables, or they can be used in expressions, like so:
$int_var = 12345;
$another_int = -12345 + 12345;
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format. Decimal format is the default, octal integers are specified with a leading 0, and hexadecimals have a leading 0x.
For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647), and the smallest (most negative) integer is . (2**31 . 1) (or .2,147,483,647).

Doubles:

They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal places needed. For example, the code:
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print(.$many + $many_2 = $few
.);
It produces the following browser output:
2.28888 + 2.21112 = 4.5

Boolean:

They have only two possible values either true or false. PHP provides a couple of constants especially for use as Booleans: TRUE and FALSE, which can be used like so:
if (TRUE)
   print("This will always print
");
else
   print("This will never print
");

Interpreting other types as Booleans:

Here are the rules for determine the "truth" of any value not already of the Boolean type:
  • If the value is a number, it is false if exactly equal to zero and true otherwise.
  • If the value is a string, it is false if the string is empty (has zero characters) or is the string "0", and is true otherwise.
  • Values of type NULL are always false.
  • If the value is an array, it is false if it contains no other values, and it is true otherwise. For an object, containing a value means having a member variable that has been assigned a value.
  • Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful).
  • Don't use double as Booleans.
Each of the following variables has the truth value embedded in its name when it is used in a Boolean context.
$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";

NULL:

NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign it like this:
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case insensitive; you could just as well have typed:
$my_var = null;
A variable that has been assigned NULL has the following properties:
  • It evaluates to FALSE in a Boolean context.
  • It returns FALSE when tested with IsSet() function.

Strings:

They are sequences of characters, like "PHP supports string operations". Following are valid examples of string
$string_1 = "This is a string in double quotes" ;
$string_2 = "This is a somewhat longer, singly quoted string" ;
$string_39 = "This string has thirty-nine characters" ;
$string_0 = "" ;  // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.

This will produce following result:
My $variable will not print!\n
My name will print
There are no artificial limits on string length – within the bounds of available memory, you ought to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both the following two ways by PHP:
  • Certain character sequences beginning with backslash (\) are replaced with special characters
  • Variable names (starting with $) are replaced with string representations of their values.
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 (\)

    PHP Operators

    What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. PHP language supports following type of operators.
    • Arithmetic Operators
    • Comparision Operators
    • Logical (or Relational) Operators
    • Assignment Operators
    • Conditional (or ternary) Operators

    The assignment operator = is used to assign values to variables in PHP.
    The arithmetic operator + is used to add values together in PHP.
    Lets have a look on all operators one by one.

    PHP Arithmetic Operators

    OperatorNameDescriptionExampleResult
    x + yAdditionSum of x and y2 + 24
    x – ySubtractionDifference of x and y5 – 23
    x * yMultiplicationProduct of x and y5 * 210
    x / yDivisionQuotient of x and y15 / 53
    x % yModulusRemainder of x divided by y5 % 2
    10 % 8
    10 % 2
    1
    2
    0
    - xNegationOpposite of x- 2
    a . bConcatenationConcatenate two strings"Hi" . "Ha"HiHa

    PHP Assignment Operators

    The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the expression on the right. That is, the value of "$x = 5" is 5.
    AssignmentSame as…Description
    x = yx = yThe left operand gets set to the value of the expression on the right
    x += yx = x + yAddition
    x -= yx = x – ySubtraction
    x *= yx = x * yMultiplication
    x /= yx = x / yDivision
    x %= yx = x % yModulus
    a .= ba = a . bConcatenate two strings

    PHP Incrementing/Decrementing Operators

    OperatorNameDescription
    ++ 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

    PHP Comparison Operators

    Comparison operators allows you to compare two values:
    OperatorNameDescriptionExample
    x == yEqualTrue if x is equal to y5==8 returns false
    x === yIdenticalTrue if x is equal to y, and they are of same type5==="5" returns false
    x != yNot equalTrue if x is not equal to y5!=8 returns true
    x <> yNot equalTrue if x is not equal to y5<>8 returns true
    x !== yNot identicalTrue if x is not equal to y, or they are not of same type5!=="5" returns true
    x > yGreater thanTrue if x is greater than y5>8 returns false
    x < yLess thanTrue if x is less than y5<8 data-blogger-escaped-returns="" data-blogger-escaped-td="" data-blogger-escaped-true="">
    x >= yGreater than or equal toTrue if x is greater than or equal to y5>=8 returns false
    x <= yLess than or equal toTrue if x is less than or equal to y5<=8 returns true

    PHP Logical Operators

    OperatorNameDescriptionExample
    x and yAndTrue if both x and y are truex=6
    y=3
    (x < 10 and y > 1) returns true
    x or yOrTrue if either or both x and y are truex=6
    y=3
    (x==6 or y==5) returns true
    x xor yXorTrue if either x or y is true, but not bothx=6
    y=3
    (x==6 xor y==3) returns false
    x && yAndTrue if both x and y are truex=6
    y=3
    (x < 10 && y > 1) returns true
    x || yOrTrue if either or both x and y are truex=6
    y=3
    (x==5 || y==5) returns false
    ! xNotTrue if x is not truex=6
    y=3
    !(x==y) returns true

    PHP Array Operators

    OperatorNameDescription
    x + yUnionUnion of x and y
    x == yEqualityTrue if x and y have the same key/value pairs
    x === yIdentityTrue if x and y have the same key/value pairs in the same order and are of the same type
    x != yInequalityTrue if x is not equal to y
    x <> yInequalityTrue if x is not equal to y
    x !== yNon-identityTrue if x is not identical to y

    PHP If … Else Conditional Statements

    The if, elseif …else and switch statements are used to take decision based on the different condition.
    Conditional statements are used to perform different actions based on different conditions.

    PHP Conditional Statements

    Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
    PHP supports following decision making statements:
    • if statement – executes some code only if a specified condition is true
    • if…else statement – executes some code if a condition is true and another code if the condition is false
    • if…else if….else statement – selects one of several blocks of code to be executed
    • switch statement – selects one of many blocks of code to be executed

    PHP – The if Statement

    The if statement is used to execute some code only if a specified condition is true.
    Syntax
     if (condition)
       {
       code to be executed if condition is true;
       }
    The example below will output "Have a good day!" if the current time is less than 20: Example:
      $t=date("H");
      if ($t<"20")
        {
        echo "Have a good day!";
        }
    ?>
    Output Result:
    Have a good day!

     

    The If…Else Statement

    Use the if….else statement to execute some code if a condition is true and another code if the condition is false.
    Syntax
    if (condition)
      code to be executed if condition is true;
    else
      code to be executed if condition is false;

    Example

    The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!":
    
    
    
    
    
    
If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces:

"; 
  echo "Have a nice weekend!";
  echo "See you on Monday!";
  }
?>

The ElseIf Statement

If you want to execute some code if one of several conditions are true use the elseif statement
Syntax
if (condition)
  code to be executed if condition is true;
elseif (condition)
  code to be executed if condition is true;
else
  code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":



The Switch Statement

If you want to select one of many blocks of code to be executed, use the Switch statement.
The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax
switch (expression)
{
case label1:
  code to be executed if expression = label1;
  break;  
case label2:
  code to be executed if expression = label2;
  break;
default:
  code to be executed
  if expression is different 
  from both label1 and label2;

}

Example

The switch statement works in an unusual way. First it evaluates given expression then seeks a lable to match the resulting value. If a matching value is found then the code associated with the matching label will be executed or if none of the lables match then statement will will execute any specified default code.




PHP Switch Statement

The switch statement is used to perform different actions based on different conditions.
Use php switch statement to select one of many blocks of code to be executed.
Syntax
  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 both label1 and label2;
  }
This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.
Example:
$favcolor="red";
switch ($favcolor)
{
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, or green!";
}
?>
 Output Result:
Your favorite color is red!

PHP Arrays

What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
  $cars1="Volvo";
  $cars2="BMW";
  $cars3="Toyota";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.

There are three different kind of arrays and each array value is accessed using an ID c which is called array index.
  • Indexed array – An array with a numeric index. Values are stored and accessed in linear fashion
  • Associative array – An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
  • Multidimensional array – An array containing one or more arrays and values are accessed using multiple indices
NOTE: Built-in array functions is given in function reference PHP Array Functions

Create an Array in PHP

In PHP, the array() function is used to create an array:
  array();

 

PHP Indexed Arrays

These arrays can store numbers, strings and any object but their index will be prepresented by numbers. By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in function reference.


/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
  echo "Value is $value
";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value )
{
  echo "Value is $value
";
}
?>

This will produce following result:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five

 

Get The Length of an Array – The count() Function

The count() function is used to return the length (the number of elements) of an array: Example:
    $cars=array("Volvo","BMW","Toyota");
  echo count($cars);
  ?>
Output Result:
  3

 

Loop Through an Indexed Array

To loop through and print all the values of an indexed array, you could use a for loop, like this:Example:
    $cars=array("Volvo","BMW","Toyota");
  $arrlength=count($cars);
  for($x=0;$x<$arrlength;$x++)
    {
    echo $cars[$x];
    echo "
";
    }
  ?>
 Output Result:
  Volvo
  BMW
  Toyota

Associative Arrays

The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.
NOTE: Don't keep associative array inside double quote while printing otheriwse it would not return any value.
Example


/* First method to associate create array. */
$salaries = array(
     "mohammad" => 2000,
     "qadir" => 1000,
     "zara" => 500
    );
echo "Salary of mohammad is ". $salaries['mohammad'] . "
";
echo "Salary of qadir is ".  $salaries['qadir']. "
";
echo "Salary of zara is ".  $salaries['zara']. "
";
/* Second method to create array. */
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
echo "Salary of mohammad is ". $salaries['mohammad'] . "
";
echo "Salary of qadir is ".  $salaries['qadir']. "
";
echo "Salary of zara is ".  $salaries['zara']. "
";
?>

This will produce following result:
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

 

Loop Through an Associative Array

To loop through and print all the values of an associative array, you could use a foreach loop, like this: Example:
    $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
  foreach($age as $x=>$x_value)
    {
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "
";
    }
  ?>
Output Result:
  Key=Peter, Value=35
  Key=Ben, Value=37
  Key=Joe, Value=43

 

Multidimensional Arrays

A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.
Example
In this example we create a two dimensional array to store marks of three students in three subjects:
This example is an associative array, you can create numeric array in the same fashion.


   $marks = array(
  "mohammad" => array
  (
  "physics" => 35,
  "maths" => 30,
  "chemistry" => 39
  ),
  "qadir" => array
                (
                "physics" => 30,
                "maths" => 32,
                "chemistry" => 29
                ),
                "zara" => array
                (
                "physics" => 31,
                "maths" => 22,
                "chemistry" => 39
                )
      );
   /* Accessing multi-dimensional array values */
   echo "Marks for mohammad in physics : " ;
   echo $marks['mohammad']['physics'] . "
";
   echo "Marks for qadir in maths : ";
   echo $marks['qadir']['maths'] . "
";
   echo "Marks for zara in chemistry : " ;
   echo $marks['zara']['chemistry'] . "
";
?>
This will produce following result:
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39

PHP Sorting Arrays

The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.

PHP – Sort Functions For Arrays

In this chapter, we will go through the following PHP array sort functions:
  • sort() – sort arrays in ascending order
  • rsort() – sort arrays in descending order
  • asort() – sort associative arrays in ascending order, according to the value
  • ksort() – sort associative arrays in ascending order, according to the key
  • arsort() – sort associative arrays in descending order, according to the value
  • krsort() – sort associative arrays in descending order, according to the key

Sort Array in Ascending Order – sort()

The following example sorts the elements of the $cars array in ascending alphabetical order:Example:
    $cars=array("Volvo","BMW","Toyota");
  sort($cars);
  ?>
Output Result:
 BMW
 Toyota
 Volvo

The following example sorts the elements of the $numbers array in ascending numerical order:Example:
    $numbers=array(4,6,2,22,11);
  sort($numbers);
  ?>
Output Result:
 2
 4
 6
 11
 22

Sort Array in Descending Order – rsort()

The following example sorts the elements of the $cars array in descending alphabetical order:Example:
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
?>
Output Result:
Volvo
Toyota
BMW

The following example sorts the elements of the $numbers array in descending numerical order:Example:
$numbers=array(4,6,2,22,11);
rsort($numbers);
?>
Output Result:
22
11
6
4
2

Sort Array in Ascending Order, According to Value – asort()

The following example sorts an associative array in ascending order, according to the value:Example:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age);
?>
Output Result:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43

Sort Array in Ascending Order, According to Key – ksort()

The following example sorts an associative array in ascending order, according to the key:Example:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
?>
Output Result:
Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35

Sort Array in Descending Order, According to Value – arsort()

The following example sorts an associative array in descending order, according to the value:Example:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);
?>
Output Result:
Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35

Sort Array in Descending Order, According to Key – krsort()

The following example sorts an associative array in descending order, according to the key:Example:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
krsort($age);
?>
Output Result:
Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37

Complete PHP Array Reference

For a complete reference of all array functions, go to our complete PHP Array Reference.
The reference contains a brief description, and examples of use, for each function!

PHP While Loops

Loops execute a block of code a specified number of times, or while a specified condition is true.

PHP Loops

Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.
In PHP, we have the following looping statements:
  • while - loops through a block of code while a specified condition is true
  • do…while – loops through a block of code once, and then repeats the loop as long as a specified condition is true
  • for - loops through a block of code a specified number of times
  • foreach - loops through a block of code for each element in an array

 

The while Loop

The while loop executes a block of code while a condition is true. If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.
Syntax
 while (condition)
   {
   code to be executed;
   }
Example
The example below first sets a variable i to 1 ($i=1;).
Then, the while loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:

$i=1;
while($i<=5)
  {
  echo "The number is " . $i . "
";
  $i++;
  }
?>

Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

The do…while Statement

The do…while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true.
Syntax
do
  {
  code to be executed;
  
}
while (condition);
Example
The example below first sets a variable i to 1 ($i=1;).
Then, it starts the do…while loop. The loop will increment the variable i with 1, and then write some output. Then the condition is checked (is i less than, or equal to 5), and the loop will continue to run as long as i is less than, or equal to 5:

$i=1;
do
  {
  $i++;
  echo "The number is " . $i . "
";
  }
while ($i<=5);
?>

Output:
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

PHP for Loop

Loops in PHP are used to execute the same block of code a specified number of times.

for Loop

The for loop is used when you know in advance how many times the script should run.
Syntax
for (init; condition; increment)
  {
  code to be executed;
  }
Parameters:
  • init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop)
  • condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment: Mostly used to increment a counter (but can be any code to be executed at the end of the iteration)
Note: The init and increment parameters above can be empty or have multiple expressions (separated by commas).
Example
The example below defines a loop that starts with i=1. The loop will continue to run as long as the variable i is less than, or equal to 5. The variable i will increase by 1 each time the loop runs:

for ($i=1; $i<=5; $i++)
  {
  echo "The number is " . $i . "
";
  }
?>

Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

The foreach Loop

The foreach loop is used to loop through arrays.
Syntax
foreach ($array as $value)
  {
  code to be executed;
  }
For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) – so on the next loop iteration, you'll be looking at the next array value.
Example
The following example demonstrates a loop that will print the values of the given array:

$x=array("one","two","three");
foreach ($x as $value)
  {
  echo $value . "
";
  }
?>

Output:
one
two
three

PHP Functions

The real power of PHP comes from its functions, In PHP, there are more than 700 built-in functions.
PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you:
  • Creating a PHP Function
  • Calling a PHP Function
In fact you hardly need to create your own PHP function because there are already more than 1000 of built-in library functions created for different area and you just need to call them according to your requirement.
Please refer to PHP Function Reference for a complete set of useful functions.

Create a PHP Function

A function will be executed by a call to the function.
Syntax
function functionName()
{
code to be executed;
}
PHP function guidelines:
  • Give the function a name that reflects what the function does
  • The function name can start with a letter or underscore (not a number)
Example
A simple function that writes my name when it is called:

function writeName()
{
echo "Kai Jim Refsnes";
}
echo "My name is ";
writeName();
?>
Output:
My name is Kai Jim Refsnes
PHP Functions – Adding parameters
To add more functionality to a function, we can add parameters. A parameter is just like a variable.
Parameters are specified after the function name, inside the parentheses.
Example 1
The following example will write different first names, but equal last name:

function writeName($fname)
{
echo $fname . " Refsnes.
";
}
echo "My name is ";
writeName("Kai Jim");
echo "My sister's name is ";
writeName("Hege");
echo "My brother's name is ";
writeName("Stale");
?>


Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes.
My brother's name is Stale Refsnes.

Example 2
Writing PHP Function with Parameters


function addFunction($num1, $num2)
{
  $sum = $num1 + $num2;
  echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>


This will display following result:
Sum of the two numbers is : 30

PHP Functions – Return values
To let a function return a value, use the return statement.
Example

function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>


Output:
1 + 16 = 17

Passing Arguments by Reference:
It is possible to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable's value.
Any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.
Following example depicts both the cases.
Passing Argument by Reference

function addFive($num)
{
   $num += 5;
}

function addSix(&$num)
{
   $num += 6;
}
$orignum = 10;
addFive( &$orignum );
echo "Original Value is $orignum
";
addSix( $orignum );
echo "Original Value is $orignum
";
?>


This will display following result:
Original Value is 15
Original Value is 21

Setting Default Values for Function Parameters:
You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
Writing PHP Function which returns value


function printMe($param = NULL)
{
   print $param;
}
printMe("This is test");
printMe();
?>



This will produce following result:
This is test

Dynamic Function Calls:
It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Following example depicts this behaviour.
Dynamic Function Calls

function sayHello()
{
   echo "Hello
";
}
$function_holder = "sayHello";
$function_holder();
?>


This will display following result:
Hello
PHP Forms Tutorial
The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.

PHP Form Handling
The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.
Example
The example below contains an HTML form with two input fields and a submit button:



Name:
Age:



When a user fills out the form above and clicks on the submit button, the form data is sent to a PHP file, called "welcome.php":
"welcome.php" looks like this:

Welcome !

You are years old.


Output could be something like this:
Welcome John!
You are 28 years old.
PHP $_GET Variable
There are two ways the browser client can send information to the web server.
·         The GET Method
·         The POST Method
In PHP, the predefined $_GET variable is used to collect values in a form with method="get".
The GET Method
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character.
http://www.test.com/index.htm?name1=value1&name2=value2
·         The GET method produces a long string that appears in your server logs, in the browser's Location: box.
·         The GET method is restricted to send upto 1024 characters only.
·         Never use GET method if you have password or other sensitive information to be sent to the server.
·         GET can't be used to send binary data, like images or word documents, to the server.
·         The data sent by GET method can be accessed using QUERY_STRING environment variable.
·         The PHP provides $_GET associative array to access all the sent information using GET method.

The $_GET Variable
The predefined $_GET variable is used to collect values in a form with method="get"
Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send.
Example


Name:
Age:

When the user clicks the "Submit" button, the URL sent to the server could look something like this:
http://www.learningfinest.blogspot.com/welcome.php?fname=Peter&age=37
The "welcome.php" file can now use the $_GET variable to collect form data (the names of the form fields will automatically be the keys in the $_GET array):
Welcome .

You are years old!

When to use method="get"?
When using method="get" in HTML forms, all variable names and values are displayed in the URL.
Note: This method should not be used when sending passwords or other sensitive information!
However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
Note: The get method is not suitable for very large variable values. It should not be used with values exceeding 2000 characters.

PHP $_POST Variable
In PHP, the predefined  $_POST variable is used to collect values in a form withmethod="post".
The POST method transfers information via HTTP headers.
Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.
Note: However, there is an 8 MB max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file).
·         The POST method does not have any restriction on data size to be sent.
·         The POST method can be used to send ASCII as well as binary data.
·         The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.
·         The PHP provides $_POST associative array to access all the sent information using GET method.
Example


Name:
Age:

When the user clicks the "Submit" button, the URL will look like this:
http://www.learningfinestblogspot.com/welcome.php
The "welcome.php" file can now use the $_POST variable to collect form data (the names of the form fields will automatically be the keys in the $_POST array):
Welcome !

You are years old.

When to use method="post"?
Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

The PHP $_REQUEST Variable
The predefined $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.
The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
Example
Welcome !

You are years old.

No comments:

Post a Comment