PHP Introduction | Day 1 | Day 2 | Day 3 | Day 4 | Day 5 |
This page will enlighten you on how to install and setup PHP along with the MySQL for running the php scripts.
Installation on windows using wamp server –
- Download WAMP server from any internet site(e.g www.wampserver.com – official site)
- Run the installation
- Start all the services of wamp server
First steps to run php scripts –
- After you have installed php on your system you can check if installation is successful or not by steps given below –
- Put your scripts into www folder of wamp(otherwise scripts will not run)
- Open the web browser
- Type http://localhost
- you will see the wamp server home page if not then your installation is not successful
To run the php script you should save the file with .php extension into www folder. Thus you can create your own folder into www directory and save your scripts into your own folder. To run the scripts directly without creating folder you can simply write file name after localhost for e.g suppose your file name is first.php then you should write http://localhost/first.php into your web browser as URL and easily run your script without putting it into your separate folder but it should be saved into www directory(Main directory to run the php script).
Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo() function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings.
You can save the following code as info.php file and run it on your browser as http://localhost/info.php
<?php phpinfo(); ?>
PHP syntax overview –
The PHP code is enclosed in special start and end processing instructions <?php and ?> that allow you to jump into and out of “PHP mode.” On servers with shorthand support enabled you can start a scripting block with <? and end with ?>. For maximum compatibility, it is recommended that you use the standard form (<?php) rather than the shorthand form. As there are many languages which contains similar syntax like xml.
Basic syntax –
The php code can be embedded into html code just as an example given below –
basic.php
<html>
<head>
<title> Basic Example </title>
</head>
<body>
<?php
echo “This is php code embedded into html”;
?>
</body>
</html>
similarly html code can be embedded in php code as follows –
example.php
<?php
echo “<b>”.”using html in php”.”</b>”;
?>
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. The file must have a .php extension. If the file has a .html extension, the PHP code will not be executed.
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”;
?>
Multi-lines comments:
They are generally used to provide pseudocode algorithms and more detailed explanations when necessary. The multiline style of commenting is the same as in C. Here is the example of multi lines comments.
<?
/* This is a comment with multiline
Purpose: Multiline Comments Demo
Subject: PHP
*/
echo “An example with multi line comments”;
?>
Exploring data types –
A variable is used to store information.
Variables in PHP
Variables are used for storing a values, like text strings, numbers or arrays. When a variable is declared, it can be used over and over again in your script.All variables in PHP start with a $ sign symbol. The correct way of declaring a variable in PHP:
$var_name = value;
New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will not work.
PHP supports eight primitive types.
Four scalar types:
- boolean
- integer
- float (floating-point number, aka double)
- string
Two compound types:
- array
- object
And finally two special types:
- resource
- NULL
The type of a variable is not usually set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.
Booleans
This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE.
Syntax
To specify a boolean literal, use the keywords TRUE or FALSE. Both are case-insensitive.
<?php
$foo=True;//assign the value TRUE to $foo variable
?>
Integers
An integer is a number of the set Z = {…, -2, -1, 0, 1, 2, …}.
Syntax
Integers can be specified in decimal (base 10), hexadecimal (base 16), or octal (base 8) notation, optionally preceded by a sign (- or +).
To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x.
Integer literals
<?php
$a=1234;//decimal number
$a=-123;//a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
?>
Floating point numbers
Floating point numbers (also known as “floats”, “doubles”, or “real numbers”) can be specified using any of the following syntaxes:
<?php
$a =1.234;
$b=1.2e3;
$c=7E-10;
?>
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<br>.);
It produces the following browser output:
2.28888 + 2.21112 = 4.5
STRINGS
A string is series of characters, where a character is the same as a byte
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.
<?
$variable = “name”;
$literally = ‘My $variable will not print!\\n’;
print($literally);
$literally = “My $variable will print!\\n”;
print($literally);
?>
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 (\)
string creation using heredoc –
The two methods above are the traditional way to create strings in most programming languages. PHP introduces a more robust string creation tool called heredoc that lets the programmer create multi-line strings without using quotations. However, creating a string using heredoc is more difficult and can lead to problems if you do not properly code your string! Here’s how to do it:
PHP Code:
$my_string = <<<TEST
Hello
Php code
welcome
TEST;
echo $my_string;
There are a few very important things to remember when using heredoc.
- Use <<< and some identifier that you choose to begin the heredoc. In this example we chose TEST as our identifier.
- Repeat the identifier followed by a semicolon to end the heredoc string creation. In this example that was TEST;
- The closing sequence TEST; must occur on a line by itself and cannot be indented!
Another thing to note is that when you output this multi-line string to a web page, it will not span multiple lines because we did not have any <br /> tags contained inside our string! Here is the output made from the code above.
Output –
Hello Php code welcome
Arrays
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
Syntax
Specifying with array()
An array can be created by the array() language construct. It takes as parameters any number of comma-separated key => value pairs.
array( key => value
, …
)
// key may only be an integer or string
// value may be any value of any type
<?php
$arr=array(“foo” => “bar”,12 => true);
echo $arr[“foo”]; // bar
echo $arr[12]; // 1
?>
If a key is not specified for a value, the maximum of the integer indices is taken and the new key will be that value plus 1. If a key that already has an assigned value is specified, that value will be overwritten.
<?php
// This array is the same as…
array(5 => 43, 32, 56, “b” => 12);
//…this array
array(5 => 43, 6 => 32, 7 => 56, “b” => 12);
?>
An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID c which is called array index.
- Numeric 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 accessedusing multiple indices
Numeric Array
These arrays can store numbers, strings and any object but their index will be prepresented by numbers. By defualt 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.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo “Value is $value <br />”;
}
/* 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 <br />”;
}
?>
</body>
</html>
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
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they ar edifferent 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
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array(
“abc”=> 2000,
“xyz” => 1000
);
echo “Salary of abc is “. $salaries[‘abc’] . “<br />”;
echo “Salary of xyz is “. $salaries[‘xyz’]. “<br />”;
/* Second method to create array. */
$salaries[‘abc’] = “high”;
$salaries[‘xyz’] = “medium”;
echo “Salary of abc is “. $salaries[‘abc’] . “<br />”;
echo “Salary of xyz is “. $salaries[‘xyz’]. “<br />”;
?>
</body>
</html>
This will produce following result:
Salary of abc is 2000
Salary of xyz is 1000
Salary of abc is high
Salary of xyz is medium
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 markes of three students in three subjects:
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
$markes = array(
“abc” => array
(
“physics” => 35,
“maths” => 30,
“chemistry” => 39
),
“xyz” => array
(
“physics” => 30,
“maths” => 32,
“chemistry” => 29
)
}
/* Accessing multi-dimensional array values */
echo “Markes for abc in physics : ” ;
echo $markes[‘abc’][‘physics’] . “<br/>”;
echo “Markes for xyz in maths : “;
echo $markes[‘xyz’][‘maths’] . “<br />”;
?>
</body>
</html>
This will produce following result:
Markes for abc in physics : 35
Markes for xyz in maths : 32
Objects
Object Initialization
To create a new object, use the new statement to instantiate a class:
<?php
class foo
{
function do_foo()
{
echo Doing foo.”;
}
}
$bar = new foo;
$bar->do_foo();
?>
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. The function is_resource() can be used to determine if a variable is a resource and get_resource_type() will return the type of resource it is.
NULL
The special NULL value represents a variable with no value. NULL is the only possible value of type NULL.
A variable is considered to be null if:
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset().
Syntax
There is only one value of type null, and that is the case-insensitive keyword NULL.
<?php
$var = NULL;
?>
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.
In PHP we have the following conditional statements:
- if statement – use this statement to execute some code only if a specified condition is true
- if…else statement – use this statement to execute some code if a condition is true and another code if the condition is false
- if…elseif….else statement – use this statement to select one of several blocks of code to be executed
- switch statement – use this statement to select one of many blocks of code to be executed
The if Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition) code to be executed if condition is true;
The following example will output “Have a nice weekend!” if the current day is Friday:
<html>
<body>
<?php
$d=date(“D”);
if ($d==”Fri”) echo “Have a nice weekend!”;
?>
</body>
</html>
Notice that there is no ..else.. in this syntax. You tell the browser to execute some code only if the specified condition is true.
The if…else Statement
Use the if….else statement to execute some code if a condition is true and another code if a 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!”:
<html>
<body>
<?php
$d=date(“D”);
if ($d==”Fri”)
echo “Have a nice weekend!”;
else
echo “Have a nice day!”;
?>
</body>
</html>
If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces:
<html>
<body>
<?php
$d=date(“D”);
if ($d==”Fri”)
{
echo “Hello!<br />”;
echo “Have a nice weekend!”;
echo “See you on Monday!”;
}
?>
</body>
</html>
The if…elseif….else Statement
Use the if….elseif…else statement to select one of several blocks of code to be executed.
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!”:
<html>
<body>
<?php
$d=date(“D”);
if ($d==”Fri”)
echo “Have a nice weekend!”;
elseif ($d==”Sun”)
echo “Have a nice Sunday!”;
else
echo “Have a nice day!”;
?>
</body>
</html>
Conditional statements are used to perform different actions based on different conditions.
The PHP Switch Statement
Use the 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
<html>
<body>
<?php
switch ($x)
{
case 1:
echo “Number 1”;
break;
case 2:
echo “Number 2”;
break;
case 3:
echo “Number 3”;
break;
default:
echo “No number between 1 and 3”;
}
?>
</body>
</html>
Looping structures –
Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.
- for – loops through a block of code a specified number of times.
- while – loops through a block of code if and as long as a specified condition is true.
- do…while – loops through a block of code once, and then repeats the loop as long as a special condition is trur.
- foreach – loops through a block of code for each element in an array.
The for loop statement
The for statement is used when you know how many times you want to execute a statement or a block of statements.
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
The initializer is used to set the start value for the counter of the num,ber of loop iterations. A variable may be declared here for this purpose and it is tradional to name it $i.
Example
The following example makes five iterations and changes the assigned value of two variables on each pass of the loop:
<html>
<body>
<?php
$a = 0;
$b = 0;
for( $i=0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}
echo (“At the end of the loop a=$a and b=$b” );
?>
</body>
</html>
This will produce following result:
At the end of the loop a=50 and b=25
The while loop statement
The while statement will execute a block of code if and as long as a test expression 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
This example decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends.
<html>
<body>
<?php
$i = 0;
$num = 50;
while( $i < 10)
{
$num–;
$i++;
}
echo (“Loop stopped at i = $i and num = $num” );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 1 and num = 40
The do…while loop statement
The do…while statement will execute a block of code at least once – it then will repeat the loop as long as a condition is true.
<!– google_ad_client = “pub-7133395778201029”; google_ad_width = 468; google_ad_height = 60; google_ad_format = “468x60_as”; google_ad_type = “image”; google_ad_channel = “”; //–>
Syntax
do
{
code to be executed;
}while (condition);
Example
The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 10:
<html>
<body>
<?php
$i = 0;
$num = 0;
do
{
$i++;
}while( $i < 10 );
echo (“Loop stopped at i = $i” );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 10
The foreach loop statement
The foreach statement is used to loop through arrays. For each pass the the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.
<!– google_ad_client = “pub-7133395778201029”; google_ad_width = 468; google_ad_height = 60; google_ad_format = “468x60_as”; google_ad_type = “image”; google_ad_channel = “”; //–>
Syntax
foreach (array as value)
{
code to be executed;
}
Example
Try out following example to list out the values of an array.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo “Value is $value <br />”;
}
?>
</body>
</html>
This will produce following result:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
The break statement
The PHP break keyword is used to terminate the execution of a loop prematurely.
The break statement is situated inside the statement block. If gives you full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed.
Example
In the following example condition test becomes true when the counter value reaches 3 and loop terminates.
<html>
<body>
<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 )break;
}
echo (“Loop stopped at i = $i” );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 3
The continue statement
The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.
Just like the break statement the continue statement is situated inside the statement blokc containing the code that the loop executes, preceded by a conditional test. For the pass encountering continue statement, rest of the loop code is skipped and next pass starts.
Example
In the following example loop prints the value of array but for which condition bceoms true it just skip the code and next valuye is printed.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
if( $value == 3 )continue;
echo “Value is $value <br />”;
}
?>
</body>
</html>
This will produce following result
Value is 1
Value is 2
Value is 4
Value is 5
n the php script you should save the file with .php extension into www folder. Thus you can create your own folder into www directory and save your scripts into your own folder. To run the scripts directly without creating folder you can simply write file name after localhost for e.g suppose your file name is first.php then you should write http://localhost/first.php into your web browser as URL and easily run your script without putting it into your separate folder but it should be saved into www directory(Main directory to run the php script).
Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo() function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings.
You can save the following code as info.php file and run it on your browser as http://localhost/info.php
<?php phpinfo(); ?>
PHP syntax overview –
The PHP code is enclosed in special start and end processing instructions <?php and ?> that allow you to jump into and out of “PHP mode.” On servers with shorthand support enabled you can start a scripting block with <? and end with ?>. For maximum compatibility, it is recommended that you use the standard form (<?php) rather than the shorthand form. As there are many languages which contains similar syntax like xml.
Basic syntax –
The php code can be embedded into html code just as an example given below –
basic.php
<html>
<head>
<title> Basic Example </title>
</head>
<body>
<?php
echo “This is php code embedded into html”;
?>
</body>
</html>
similarly html code can be embedded in php code as follows –
example.php
<?php
echo “<b>”.”using html in php”.”</b>”;
?>
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. The file must have a .php extension. If the file has a .html extension, the PHP code will not be executed.
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”;
?>
Multi-lines comments: They are generally used to provide pseudocode algorithms and more detailed explanations when necessary. The multiline style of commenting is the same as in C. Here is the example of multi lines comments.
<?
/* This is a comment with multiline
Purpose: Multiline Comments Demo
Subject: PHP
*/
echo “An example with multi line comments”;
?>
Exploring data types –
A variable is used to store information.
Variables in PHP
Variables are used for storing a values, like text strings, numbers or arrays. When a variable is declared, it can be used over and over again in your script.All variables in PHP start with a $ sign symbol. The correct way of declaring a variable in PHP:
$var_name = value;
New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will not work.
PHP supports eight primitive types.
Four scalar types:
boolean
integer
float (floating-point number, aka double)
string
Two compound types:
array
object
And finally two special types:
resource
NULL
The type of a variable is not usually set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.
Booleans
This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE.
Syntax
To specify a boolean literal, use the keywords TRUE or FALSE. Both are case-insensitive.
<?php
$foo=True;//assign the value TRUE to $foo variable
?>
Integers
An integer is a number of the set Z = {…, -2, -1, 0, 1, 2, …}.
Syntax
Integers can be specified in decimal (base 10), hexadecimal (base 16), or octal (base 8) notation, optionally preceded by a sign (- or +).
To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x.
Integer literals
<?php
$a=1234;//decimal number
$a=-123;//a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
?>
Floating point numbers
Floating point numbers (also known as “floats”, “doubles”, or “real numbers”) can be specified using any of the following syntaxes:
<?php
$a =1.234;
$b=1.2e3;
$c=7E-10;
?>
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<br>.);
It produces the following browser output:
2.28888 + 2.21112 = 4.5
STRINGS
A string is series of characters, where a character is the same as a byte
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.
<?
$variable = “name”;
$literally = ‘My $variable will not print!\\n’;
print($literally);
$literally = “My $variable will print!\\n”;
print($literally);
?>
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 (\)
string creation using heredoc –
The two methods above are the traditional way to create strings in most programming languages. PHP introduces a more robust string creation tool called heredoc that lets the programmer create multi-line strings without using quotations. However, creating a string using heredoc is more difficult and can lead to problems if you do not properly code your string! Here’s how to do it:
PHP Code:
$my_string = <<<TEST
Hello
Php code
welcome
TEST;
echo $my_string;
There are a few very important things to remember when using heredoc.
Use <<< and some identifier that you choose to begin the heredoc. In this example we chose TEST as our identifier.
Repeat the identifier followed by a semicolon to end the heredoc string creation. In this example that was TEST;
The closing sequence TEST; must occur on a line by itself and cannot be indented!
Another thing to note is that when you output this multi-line string to a web page, it will not span multiple lines because we did not have any <br /> tags contained inside our string! Here is the output made from the code above.
Output –
Hello Php code welcome
Arrays
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
Syntax
Specifying with array()
An array can be created by the array() language construct. It takes as parameters any number of comma-separated key => value pairs.
array( key => value
, …
)
// key may only be an integer or string
// value may be any value of any type
<?php
$arr=array(“foo” => “bar”,12 => true);
echo $arr[“foo”]; // bar
echo $arr[12]; // 1
?>
If a key is not specified for a value, the maximum of the integer indices is taken and the new key will be that value plus 1. If a key that already has an assigned value is specified, that value will be overwritten.
<?php
// This array is the same as…
array(5 => 43, 32, 56, “b” => 12);
//…this array
array(5 => 43, 6 => 32, 7 => 56, “b” => 12);
?>
An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID c which is called array index.
Numeric 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 accessedusing multiple indices
Numeric Array
These arrays can store numbers, strings and any object but their index will be prepresented by numbers. By defualt 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.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo “Value is $value <br />”;
}
/* 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 <br />”;
}
?>
</body>
</html>
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
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they ar edifferent 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
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array(
“abc”=> 2000,
“xyz” => 1000
);
echo “Salary of abc is “. $salaries[‘abc’] . “<br />”;
echo “Salary of xyz is “. $salaries[‘xyz’]. “<br />”;
/* Second method to create array. */
$salaries[‘abc’] = “high”;
$salaries[‘xyz’] = “medium”;
echo “Salary of abc is “. $salaries[‘abc’] . “<br />”;
echo “Salary of xyz is “. $salaries[‘xyz’]. “<br />”;
?>
</body>
</html>
This will produce following result:
Salary of abc is 2000
Salary of xyz is 1000
Salary of abc is high
Salary of xyz is medium
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 markes of three students in three subjects:
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
$markes = array(
“abc” => array
(
“physics” => 35,
“maths” => 30,
“chemistry” => 39
),
“xyz” => array
(
“physics” => 30,
“maths” => 32,
“chemistry” => 29
)
}
/* Accessing multi-dimensional array values */
echo “Markes for abc in physics : ” ;
echo $markes[‘abc’][‘physics’] . “<br/>”;
echo “Markes for xyz in maths : “;
echo $markes[‘xyz’][‘maths’] . “<br />”;
?>
</body>
</html>
This will produce following result:
Markes for abc in physics : 35
Markes for xyz in maths : 32
Objects
Object Initialization
To create a new object, use the new statement to instantiate a class:
<?php
class foo
{
function do_foo()
{
echo Doing foo.”;
}
}
$bar = new foo;
$bar->do_foo();
?>
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. The function is_resource() can be used to determine if a variable is a resource and get_resource_type() will return the type of resource it is.
NULL
The special NULL value represents a variable with no value. NULL is the only possible value of type NULL.
A variable is considered to be null if:
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset().
Syntax
There is only one value of type null, and that is the case-insensitive keyword NULL.
<?php
$var = NULL;
?>
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.
In PHP we have the following conditional statements:
if statement – use this statement to execute some code only if a specified condition is true
if…else statement – use this statement to execute some code if a condition is true and another code if the condition is false
if…elseif….else statement – use this statement to select one of several blocks of code to be executed
switch statement – use this statement to select one of many blocks of code to be executed
The if Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition) code to be executed if condition is true;
The following example will output “Have a nice weekend!” if the current day is Friday:
<html>
<body>
<?php
$d=date(“D”);
if ($d==”Fri”) echo “Have a nice weekend!”;
?>
</body>
</html>
Notice that there is no ..else.. in this syntax. You tell the browser to execute some code only if the specified condition is true.
The if…else Statement
Use the if….else statement to execute some code if a condition is true and another code if a 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!”:
<html>
<body>
<?php
$d=date(“D”);
if ($d==”Fri”)
echo “Have a nice weekend!”;
else
echo “Have a nice day!”;
?>
</body>
</html>
If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces:
<html>
<body>
<?php
$d=date(“D”);
if ($d==”Fri”)
{
echo “Hello!<br />”;
echo “Have a nice weekend!”;
echo “See you on Monday!”;
}
?>
</body>
</html>
The if…elseif….else Statement
Use the if….elseif…else statement to select one of several blocks of code to be executed.
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!”:
<html>
<body>
<?php
$d=date(“D”);
if ($d==”Fri”)
echo “Have a nice weekend!”;
elseif ($d==”Sun”)
echo “Have a nice Sunday!”;
else
echo “Have a nice day!”;
?>
</body>
</html>
Conditional statements are used to perform different actions based on different conditions.
The PHP Switch Statement
Use the 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
<html>
<body>
<?php
switch ($x)
{
case 1:
echo “Number 1”;
break;
case 2:
echo “Number 2”;
break;
case 3:
echo “Number 3”;
break;
default:
echo “No number between 1 and 3”;
}
?>
</body>
</html>
Looping structures –
Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.
for – loops through a block of code a specified number of times.
while – loops through a block of code if and as long as a specified condition is true.
do…while – loops through a block of code once, and then repeats the loop as long as a special condition is trur.
foreach – loops through a block of code for each element in an array.
The for loop statement
The for statement is used when you know how many times you want to execute a statement or a block of statements.
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
The initializer is used to set the start value for the counter of the num,ber of loop iterations. A variable may be declared here for this purpose and it is tradional to name it $i.
Example
The following example makes five iterations and changes the assigned value of two variables on each pass of the loop:
<html>
<body>
<?php
$a = 0;
$b = 0;
for( $i=0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}
echo (“At the end of the loop a=$a and b=$b” );
?>
</body>
</html>
This will produce following result:
At the end of the loop a=50 and b=25
The while loop statement
The while statement will execute a block of code if and as long as a test expression 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
This example decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends.
<html>
<body>
<?php
$i = 0;
$num = 50;
while( $i < 10)
{
$num–;
$i++;
}
echo (“Loop stopped at i = $i and num = $num” );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 1 and num = 40
The do…while loop statement
The do…while statement will execute a block of code at least once – it then will repeat the loop as long as a condition is true.
<!– google_ad_client = “pub-7133395778201029”; google_ad_width = 468; google_ad_height = 60; google_ad_format = “468x60_as”; google_ad_type = “image”; google_ad_channel = “”; //–>
Syntax
do
{
code to be executed;
}while (condition);
Example
The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 10:
<html>
<body>
<?php
$i = 0;
$num = 0;
do
{
$i++;
}while( $i < 10 );
echo (“Loop stopped at i = $i” );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 10
The foreach loop statement
The foreach statement is used to loop through arrays. For each pass the the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.
<!– google_ad_client = “pub-7133395778201029”; google_ad_width = 468; google_ad_height = 60; google_ad_format = “468x60_as”; google_ad_type = “image”; google_ad_channel = “”; //–>
Syntax
foreach (array as value)
{
code to be executed;
}
Example
Try out following example to list out the values of an array.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo “Value is $value <br />”;
}
?>
</body>
</html>
This will produce following result:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
The break statement
The PHP break keyword is used to terminate the execution of a loop prematurely.
The break statement is situated inside the statement block. If gives you full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed.
Example
In the following example condition test becomes true when the counter value reaches 3 and loop terminates.
<html>
<body>
<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 )break;
}
echo (“Loop stopped at i = $i” );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 3
The continue statement
The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.
Just like the break statement the continue statement is situated inside the statement blokc containing the code that the loop executes, preceded by a conditional test. For the pass encountering continue statement, rest of the loop code is skipped and next pass starts.
Example
In the following example loop prints the value of array but for which condition bceoms true it just skip the code and next valuye is printed.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
if( $value == 3 )continue;
echo “Value is $value <br />”;
}
?>
</body>
</html>
This will produce following result
Value is 1
Value is 2
Value is 4
Value is 5