Introduction


Firstly started developing of PHP was started by Rasmus lerdorf in the form of PHP /FI. Eventually it leads to the development of PHP known by us today. The first version of PHP is called as personal homepage tools/Form Interpreter.

Many of the features are introduced form the middle level and high level language like c and java. Second version is PHP /FI2 in the second version many common features which were lacking is introduced.

Third version came up the new name for the PHP that is hypertext preprocessor; to emphasize that PHP was different product only suitable for personal use. Zeev introduced a new feature called API in the third version of the PHP and it is released in the year 1998 June , at the end of the 1998 Zeev felt they could have written the scripting language even better he started another rewrite.

He came up with a new idea of paradigm of compile first execute later. The compilation step does not compile PHP script into machine code, it instead complies into byte code which is then executed by the Zend engine. It Is officially released in the year may 22, 2002, and has surpassed 15million domains. Soon after php5 was introduced with object oriented features were introduced in Zend engine..

Where do you start?.

Using PHP in the creation of powerful, dynamic web applications; you’ll also begin to develop the basic skills you need to create your blog.

Embed PHP in web pages.

Send data as output to the browser.

Add comments in your code.

Use operators to manipulate data.

Use control structures to add power to your scripts..

Only time will tell if the PHP 5 release will be as successful as its two predecessors(PHP 3 and PHP 4). The new features and changes aim to rid PHP of any weaknesses it may have had and make sure that it stays in the lead as the world’s best web-scripting language.

Language Features


It was added as “syntactic sugar for accessing collections.” The OO model also had support for inheritance and allowed a class (and object) to aggregate both methods and properties, but not much more. When Zeev rewrote the scripting engine for PHP 4, it was a completely new engine; it ran much faster, was more stable, and boasted more features. However, the OO model first introduced in PHP 3 was barely touched. Although the object model had serious limitations, it was used extensively around the world, often in large PHP applications. This impressive use of the OOP paradigm with PHP 4, despite its weaknesses, led to it being themain focus for the PHP 5 release.

Some of the PHP strengths


Some of the php main competitors are Perl Microsoft Asp.net , java server page and cold fusion.

In comparison to these products php has many strengths .

High performance.

Interface to many databases.

Built in lib for many web tasks.

Low cost.

Portability.

Availability of source code.

Availability of support.

Embedded


How a server will process PHP in a file before sending that file to the browser. But you might be curious how the server knows where to look for PHP.

By default, servers look for PHP only in files that end with the .php extension. But a .php file can Contain elements that aren’t part of your PHP script, and searching the entire file for potential scripts is confusing and resource-intensive.

For example:-

  1. <p>Static Text</p>
  2. <p><?php echo '<p> This text was generated by me in php!</p>';?>
  3. <p> This is a html text <p>

Save it as PHP file and execute in xammp or wamp servers. You could see the out put in your browser.

Result

_______________________________________________________ Static text. This text was generated by me in PHP!. This is a html text. _________________________________________________________

As you can see, the text inside the PHP delimiters was handled as a script, but the text outside was rendered as regular HTML. There is no limit to how many blocks of PHP you can include in a page, so the following snippet is completely valid.

            
  1. <?php echo '<p>This is some text.</p>';?>
  2. <p>Some of this text is static, <?php echo 'but this sure isn't!'; ?></p>
  3. <?php echo '<p>'; ?>
  4. This text is enclosed in paragraph tags that were generated by PHP.
  5. <?php echo '</p>'; ?>

Save it as PHP file and execute in xammp or wamp servers. You could see the out put in your browser.

___________________________________________________________________ This is some text. Some of this text is static, but this sure isn't! This text is enclosed in paragraph tags that were generated by PHP. ___________________________________________________________________

PHP offers a shortcut syntax known as short tags; these allow your scripts to be delimited with

<? and ?>
          
which is easier to type. However, the use of short tags requires that the short_open_tag directive be enabled, which means that scripts using short tags can create compatibility problems for applications that need to run on multiple servers that might not have the same configuration.

For Example:-

There is also a shortcut syntax for outputting data quickly, which you use like this:

  1. <?='Some text to output.'?>
  2. The previous snippet functions identically to this longer-winded syntax:
  3. <?php echo 'Some text to output.';?>

Again, keep in mind that you should avoid using this syntax because of its incompatibility, both with various server configurations and XML syntax.

VARIABLES AND DATATYPES


you’ve learned how to output data, as well as how to use variables to a certain extent. Before going any further, let’s take a moment to drill down on variables and how they work.


What Is a Variable?

A variable is a keyword or phrase that acts as an identifier for a value stored in a system’s memory. This is useful because it allows us to write programs that will perform a set of actions on a variable value, which means you can change the output of the program simply by changing the variable, rather than changing the program itself. Storing Values in a Variable PHP lets you store nearly anything in a variable using one of the following datatypes:

String: Alphanumeric characters, such as sentences or names.

Integer: A numeric value, expressed in whole numbers.

Float: A numeric value, expressed in real numbers (decimals).

Boolean: Evaluates to TRUE or FALSE (sometimes evaluates to 1 for TRUE and 0 for FALSE).

Array: An indexed collection of data.

Object: A collection of data and methods.

PHP is a loosely typed language, which means it determines the type of data being handled based on a “best guess” principle, as opposed to a strictly typed language such as C, which requires you name datatypes for every variable and function. Consider this code snippet:

$foo = "5"; // This is considered a string.

$bar = $foo + 2; // This converts $foo to an integer (outputs 7).

This might seem confusing at first, but it’s actually intuitive and eliminates debugging if you enclose a number in quotes accidentally.

Strings


Strings in PHP are a sequence of characters that are always internally null terminated. However, unlike some other languages, such as C, PHP does not rely on the terminating null to calculate a string’s length, but remembers its length internally. This allows for easy handling of binary data in PHP.

For example, creating an image on-the-fly and outputting it to the browser. The maximum length of strings varies according to the platform and C compiler, but you can expect it to support at least 2GB. Don’t write programs that test this limit because you’re likely to first reach your memory limit. When writing string values in your source code, you can use double quotes ("), single quotes (') or here-docs to delimit them.

Single-Quote Syntax

Enclosing a string in single quotes is the simplest way to create a string in PHP. It doesn’t expand special characters or variables, but instead delivers them as plain text to the browser.

PHP lets you store nearly anything in a variable using one of the following datatypes:

Let’s look at some examples to see how single quotes behave.

Add the following into example.php to see how different data is handled:

  1.  <?php
  2.  // The <br /> adds a line break in the browser for readability
  3.  echo 'This is a string. <br />';
  4.  echo 'This is a string with line breaks. <br />';
  5.  // Special characters, such as the newline (\n) character,
  6.  // won't be expanded when in single quotes.
  7.  echo 'This is a string \n with a newline character. <br />';
  8.  echo 'This string\'s got an apostrophe. <br />';
  9.  // A backslash doesn't need to be escaped if not escaping a
  10. // special character.
  11.  echo 'This string has a backslash (\) in it. <br />';
  12.  echo 'This string has an escaped backslash (\\) in it. <br />';
  13. // Variables will not be expanded in single quotes
  14.  echo 'This $variable will not be expanded. <br />';
  15.  ?>

Double-Quote Syntax

Strings encased in double quotes behave similarly to strings encased in single quotes but they interpret more special characters, including expanding variables.

You can see the difference achieved by placing strings in double quotes by placing the following code in Example.php:

  1.  <?php echo "This is a string. <br />";
  2.  echo "This is a string that spans multiple lines. <br />";
  3.  // Apostrophes don't need to be escaped in double quotes
  4.  echo "This string's got an apostrophe. <br />";
  5.  // Double quotes will need to be escaped
  6.  echo "This string says, \"I need escaping!\" <br />";
  7.  // New line characters will be interpreted
  8.  echo "This string has \n newline \n characters. <br />";
  9.  // A backslash will be printed if a special character doesn't
  10.  // directly follow it
  11.  echo "This string contains a backslash (\). <br />";
  12.  // Variables will be expanded if not escaped
  13.  $variable = "word";
  14.  echo "This string uses a $variable. <br />";
  15.  // A variable can be interpreted as plain text by escaping the
  16. // dollar sign with a backslash
  17.  echo "This string escapes the \$variable. <br />";
  18.  ?>

String Concatenation

It’s often necessary to join two strings together in a script. You accomplish this using the string Concatenation operator, a period (.).

You join two strings together by placing a period between them:

  1. <?php
  2.  $raa = "This is a " . "string.";
  3.  echo $raa;
  4.  ?>

You can concatenate variables as well, as long as they’re not of the array or object type:

  1. <?php
  2. $raa = "This is a ";
  3. $mee = "string.";
  4. echo $raa . $mee;
  5. ?>

Integers Floating Point & Boolean Values


An integer is any positive or negative whole number (a number without a decimal value).

For example, the numbers 1, -27, and 4985067 are integers, but 1.2 is not.

Because PHP is a loosely typed language, it’s not necessary to declare a variable as an integer; however, if you find it necessary, you can explicitly cast, or force, a value as an integer using the following syntax:.

  1. $raa = 27; // No quotes around a whole number always means integer
  2. $baa = (int) "3-peat"; // Evaluates to 3
  3. $maa = (int) "seven"; // Evaluates to 0
  4. $taa = (int) "ten 4"; // Evaluates to 0

Where do you start?.

Using PHP in the creation of powerful, dynamic web applications; you’ll also begin to develop the basic skills you need to create your blog.

Floating Point Numbers

Floating point numbers (also known as floats or doubles) are numbers with decimal values, or real numbers. This includes numbers such as 3.14, 5.33333, and 1.1.

Note that floating point numbers can produce unexpected results due to the fact that it’simpossible to represent all values with a finite number of digits.

A good example of this is 1/3, which evaluates to a repeating decimal (0.33333...). You should not use floating point numbers to compare equality for this reason.

Boolean Values

A Boolean value is the simplest type of data; it represents truth, and can contain only one of two values TRUE or FALSE.

It’s important to note that the FALSE (not in quotes) Boolean value is different from the "FALSE" string value, and the same goes for TRUE. Boolean values are not case sensitive.Booleans are very useful when determining if a condition exists. For example, you can use an if-else statement (which I’ll cover in a moment) to perform different actions if a condition is TRUE:

  1. if($condition===true)
  2.   {
  3. echo 'The condition is true!';
  4.    }
  5. else
  6.   {
  7. echo 'The condition is false!';
  8.   }

Arrays


Arrays are among the most powerful datatypes available in PHP, due to their ability to map information using a key to value pairing. This means that an array can store multiple pieces of information in a single variable, all indexed by key. For instance, if you have a blog entry to store in variables, you would need to do the following if you didn’t use arrays:

  1. <?php
  2. $entryTitle = "your Title";
  3. $entryDate = "August 20, 2015";
  4. $entryAuthor = "santhu";
  5. $entryBody = "Today, ihave done my first entry.";
  6. ?>

This can become confusing, especially if the entry needs to be passed to a function for processing. You can use an array to simplify the entry:

  1. <?php
  2. $entry = array(
  3. 'title' => 'Any Title',
  4. 'date' => 'Aug 20, 2015',
  5. 'author' => 'Ravi',
  6. 'body' => 'Today, ihave done my entry.'
  7.  );
  8. ?>

Multidimensional Arrays.

The array we used in the last example was a one dimensional array. Arrays can have more than one dimension, these arrays-of-arrays are called multidimensional arrays. They are very similar to standard arrays with the exception that they have multiple sets of square brackets after the array identifier. A two dimensional array can be though of as a grid of rows and columns.

  1.  <?php
  2.  $people = array(
  3.  array('name' => 'santhu', 'age' => 23), // $people[0]
  4.  array('name' => 'samsu', 'age' => 18) // $people[1]
  5.     );
  6.  echo "{$people[0]['name']} has a sister who is
  7.  {$people[1]['age']} years old.";
  8.     ?>

COMMENTS


There are several ways to write comments in PHP, but only two are encouraged. For inline comments, you can use two forward slashes (//); for block comments, you can start with a forward slash followed by an asterisk (/*), then close with an asterisk followed by a forward slash (*/).

  1. $foo = 'some value'; // This is an inline C++ comment
  2.  /*
  3. This is a block comment in C style. It allows the developer to go into more detail about the code.
  4. */
  5. function bar() {
  6. return true;
  7. }
  8. Inline vs. Block Comments
  9. There’s not really a right or wrong way to comment code, but accepted practice is to use inline
  10. comments for quick descriptions, such as the purpose of a variable:
  11. <?php
  12. $foo = time()+7*24*60*60; // One week from now
  13. ?>
  14. A block-level comment is typically used when more detail is necessary. For example, this
  15. comment might be used to describe an entire section of code:

OPERATORS


PHP, like many other programming languages, provides a number of operators that allow you to manipulate data. These operators fall into several categories;

• Arithmetic Operators: These perform basic mathematical functions.

• Arithmetic Assignment Operators: These set expression values.

• Comparison Operators: These determine the similarity of two values.

• Error Control Operators: These special operators to suppress errors.

• Incrementing/Decrementing Operators: These increase or decrease a value.

• Logical Operators: These denote logical operations; examples include AND and OR

• String Operators: These manipulate strings.


ARITHMETIC OPERATORS

The arithmetic operators in PHP function just like the ones you used in school. The addition operator (+) returns the sum of two values:

  1.  echo 2 + 2; // Outputs 4
  2.  The subtraction operator (-) returns the difference between two values:
  3.  echo 4 – 2; // Outputs 2
  4.  The multiplication operator (*) returns the product of two values:
  5.  echo 4 * 2; // Outputs 8
  6.  The division operator (/) returns the quotient of two values:
  7.  echo 8 / 2; // Outputs 4

ARITHMETIC ASSIGNMENT OPERATORS

PHP provides several assignment operators that enable you to set the value of an operand to the value of an expression. You do this with an equals sign (=), but it’s important to be aware that this sign does not mean “equals” as it is commonly understood; instead, this symbol means “gets set to.”

For example,consider this code snippet:

  1. $a = 5,
  2.   Example 1
  3. <?php
  4.  $daa = 2;
  5.  $daa += 2; // New value is 4
  6.  $daa -= 1; // New value is 3
  7.  $daa *= 4; // New value is 12
  8.  $daa /= 2; // New value is 6
  9.  $daa %= 4; // New value is 2
  10.                 ?>
  11.  Example 2
  12.  <?php
  13.   $daa = 2;
  14.   $bus = $daa;
  15.   echo $bus; // Output: 2
  16.   $daa += 4; // New value is 6
  17.   echo $bus; // Output: 2
  18.   ?>

COMPARISON OPERATORS

You use comparison operators to determine the similarity between values. These are especially useful in control structures.

The available comparison operators allow you to determine whether the following conditionsare present between two values:

• (==): Values are equal • (===): Values are identical • (!= or <>): Values are not equal • (!==): Values are not identical • (<): Value 1 is less than value 2 • (>): Value 1 is greater than value 2 • (<=): Value 1 is less than or equal to value 2 • (>=): Value 1 is greater than or equal to value 2

INCREMENTING/DECREMENTING OPERATORS

In some scripts, it becomes necessary to add or subtract one from a value quickly. PHP provides an easy way to do this with its incrementing and decrementing operators.To add one to a value, add two plus signs (++) before or after the variable. To subtract one, add two minus signs (--)—remember that placing the (++) or (--) operators before a variable increments or decrements the variable before it is instantiated, while placing these operators after a variable increments or decrements the variable after it is instantiated. Adding signs in front of the variable is called prepending, which means the variable is incremented or decremented before it is instantiated:.

  1. <?php
  2.  $foo = 5;
  3.  ++$foo; // New value is 6
  4.  $foo++; // New value is 7
  5.  --$foo; // New value is 6
  6.  $foo--; // New value is 5
  7.   $bar = 4;
  8. // Echo a prepended value
  9.  echo ++$bar; // Output is 5, new value is 5
  10. // Echo a postpended value
  11.   echo $bar++; // Output is 5, new value is 6
  12.   ?>

LOGICAL OPERATORS

Logical operators allow you to determine whether two conditions are true or not. This is very useful when using conditional statements to dictate what happens in a program. PHP’s available operators include:

• AND or &&: Returns true if both expressions are true.

• OR or ||: Returns true if at least one expression is true.

• XOR: Returns true if one expression is true, but not the other.

• !: Returns true if the expression is not true.

  1. <?php
  2.  $raa = true;
  3.  $bee = false;
  4.  // Print the statement if $foo AND $bar are true
  5.  if($raa && $bee) {
  6.  echo 'Both $raa and $bee are true. <br />';
  7.                   }
  8.  // Print the statement if $raa OR $bee is true
  9.  if($raa || $bee) {
  10.  echo 'At least one of the variables is true. <br />';
  11.                    }
  12.  // Print the statement if $raa OR $bee is true, but not both
  13.  if($raa xor $bee) {
  14.  echo 'One variable is true, and one is false. <br />';
  15.                     }
  16.  // Print the statement if $bee is NOT true
  17.   if(!$bee) {
  18.  echo '$bee is false. <br />';
  19.              }
  20.   ?>

STRING OPERATORS

There are two string operators available in PHP: the concatenation operator (.) and the concatenating assignment operator (.=). The concatenation operator combines two strings into one by joining the end of the string to the left of the operator to the beginning of the string on the right of the operator. The concatenating assignment operator adds a string to the end of an existing variable:

  1. <?php
  2.  $raa = "Hello";                     
  3.  $bee = $raa . " world! <br />";                     
  4.  echo $bee; // Output: Hello world!
  5.  $bee .= "  And again!";
  6.  echo $bee; // Output: Hello world! And again!
  7.  ?>

control structures


PHP supports a number of conditional statements, loops, and other control structures that allow us to manipulate data easily throughout your code.

The control structures supported by PHP are: • if • else • elseif/else if • while • do-while • for • foreach • break • continue • switch • return • require • include • require_once • include_once • goto

IF, ELSE, AND ELSE IF

The most basic control structure is the if statement. It defines a block of code between curly braces ({}) that is to be executed only if a condition is met:

Using PHP in the creation of powerful, dynamic web applications; you’ll also begin to develop the basic skills you need to create your blog.

  1. <?php
  2. $raa = 5;
  3. if($raa < 10) {
  4. echo "The condition was met. <br />";
  5.               }
  6. ?>

In this program, nothing is output if $raa doesn’t meet your condition. In some cases, this is an Unacceptable result, so you would need to use an else statement to provide an alternative value to output if the condition isn’t met:

  1. <?php
  2. $flee = 15;
  3. if($flee < 10) {
  4. echo "The condition was met. <br />";
  5.                 } else {
  6. echo "The condition was not met. <br />";
  7.                   }
  8. ?>

If you have a value that failed the if condition, but you aren’t ready to pass it to the else statement yet, you can add an else if statement to be evaluated. You place this new statement between the if and else blocks; it executes only if the first condition isn’t met, but the second is:

  1. <?php
  2. if($age < 18) {
  3. echo "Not old enough to vote or drink! <br />";
  4. } else if ($age < 21) {
  5. echo "Old enough to vote, but not to drink. <br />";
  6. } else { // If we get here, $age is >= 21
  7.  echo "Old enough to vote and drink! <br />";
  8. };
  9. ?>

WHILE AND DO-WHILE

The while loop allows you to repeat a block of code continuously for as long as a condition is TRUE. This allows you to cycle through data sets without needing to know how many exist; all that matters is the number of datasets you want to use at a maximum.

In this example, you use a counter variable ($i) that stores the count, incrementing this at the end of each loop cycle. When the counter reaches three, the condition is no longer true, so the loop ends.

  1. <?php
  2.  $i = 0;
  3. while($i<3) {              
  4. echo "Count is at $i. <br />";              
  5.  ++$i;             
  6.  }
  7.  ?>             
  8. A more practical example is looping through an array to generate output based on the stored
  9. values. 
  10.  <?php
  11.   $bands = array("Minus the Bear", "The Decemberists",
  12.   "Neko Case", "Bon Iver", "Now It's Overhead");
  13.    $i = 0;
  14.    $n = count($bands); // Stores the number of values in the array
  15.    while($i < $n) {
  16.    echo $bands[$i], "<br />";
  17.    ++$i;
  18.     }
  19.    ?>

FOR

One of the most versatile statements in PHP programming is the for loop, which accepts three expressions: expression one is evaluated once at the beginning of the loop, unconditionally; expression two is evaluated at the beginning of each iteration of the loop, and the loop continues only if the expression evaluates to true; expression three is evaluated at the end of each iteration. Each expression can have more than one part, with each part separated by a comma. You separate the three main expressions using semicolons:

  1. <?php
  2. for($i=0; $i<3; ++$i) {
  3.  echo "The count is at $i.\n";
  4.   }
  5. ?>
  6.  // Output:
  7. // The count is at 0.
  8. // The count is at 1.
  9. // The count is at 2.

At this point, you might find it helpful to revisit the previous code example where you created a list of bands. This code produces output identical to the while loop you used previously, while also cleaning up the code a bit:

  1. <?php
  2. $bands = array("Minus the Bear", "The Decemberists",
  3. "Neko Case", "Bon Iver", "Now It's Overhead");
  4. for($i=0, $n=count($bands); $i<$n; ++$i) {
  5. echo $bands[$i], "<br />";
  6. }
  7. ?>

FOREACH

The foreach loop provides a powerful option for cases where you deal with arrays. Continuing with the code example that outputs a list of bands, you can use foreach to cycle quickly through the array elements:

  1. <?php
  2. $bands = array("Minus the Bear", "The Decemberists",
  3.  "Neko Case", "Bon Iver", "Now It's Overhead");
  4.  foreach($bands as $band) {
  5.  echo $band, "<br />";
  6.  }
  7. ?>

The foreach loop lets you iterate through an array and treat each array element as an individual variable; this makes for very readable code. If the array is associative, you also have the option to separate the array key as a variable. This proves useful in some cases.:

  1. <?php
  2.  $person = array(
  3.  'name' => 'raja',
  4.  'age' => 23,
  5.  'passion' => 'choclates'
  6.   );
  7.  foreach($person as $key => $value) {
  8.  echo "His $key is $value. <br />";
  9.  }
  10. ?>

BREAK

the break statement causes the loop to end. In the case of nested loops, a numeric argument can be passed to tell the break statement how many loops to run before breaking out of the loop:

  1. <?php
  2.  $person = array(
  3.  'name' => 'raja',
  4.  'age' => 23,
  5.  'passion' => 'choclates'
  6.   );
  7.  foreach($person as $key => $value) {
  8.  echo "His $key is $value. <br />";
  9.  }
  10. ?>

STRING OPERATORS

There are two string operators available in PHP: the concatenation operator (.) and the concatenating assignment operator (.=). The concatenation operator combines two strings into one by joining the end of the string to the left of the operator to the beginning of the string on the right of the operator. The concatenating assignment operator adds a string to the end of an existing variable:

  1. <?php
  2. $raa = "Hello";
  3. $bee = $raa . " world! <br />";
  4. echo $bee; // Output: Hello world!
  5. $bee .= "  And again!";
  6. echo $bee; // Output: Hello world! And again!
  7. ?>

FUNCTIONS


The most powerful feature of PHP is the ability to define and execute functions from within your code. A function is a named block of code that you declare within your scripts that you can call at a later time. Functions can accept any number of arguments and can return a value using the return statement.

The basic format of a function requires that you first identify the function using the function reserved word in front of a string that serves as the function’s name. This string can contain any alphanumeric characters and underscores, but it must not start with a number. You enclose any arguments you want in parentheses after the function name. Note that you still must include the parentheses even if the function doesn’t require that you pass any arguments.

  1. <?php
  2. function sayHello()
  3.        {
  4. echo "Hello india!";
  5.         }
  6. // Execute the function
  7. sayHello();
  8. ?>

To add arguments, you place variables inside the function declaration’s parentheses, separated by commas. You can use these arguments within the function to determine the function’s return value:

  1. <?php
  2. function meet($name)
  3.       {
  4. echo "Hello, my name is $name. Nice to meet you! <br />";
  5.        }
  6. meet("raj");
  7.  ?>

RETURNING VALUES FROM FUNCTIONS

Most of the time, you won’t want to immediately the result of a function call immediately. To store the result in a variable, you use the return statement discussed earlier.

  1. <?php
  2. /*
  3. * Based on the time passed to the function in military (24 hour)
  4. * time, returns a greeting
  5. */
  6. function greet($time)
  7.     {
  8. if($time<12)
  9.     {
  10. return "Good morning!";
  11.      }
  12. elseif($time<18)
  13.      {
  14. return "Good afternoon!";
  15. else
  16.     {
  17. return "Good evening!";
  18.      }
  19.      }
  20. $greeting = greet(14);
  21. echo "$greeting How are you?";
  22.  ?>