SlideShare une entreprise Scribd logo
1  sur  105
Course Instructor: Nisa Soomro
 PHP and MySQL Web Development Fourth Edition “Luke Welling, Laura Thomson” 
 http://sage.math.washington.edu/home/wstein/www/home/agc/lit/php/PHPMySQL.pdf 
 www.W3school.com 
2
PHP Intro 
PHP Install 
PHP Syntax 
PHP Variables 
PHP Echo / Print 
PHP Data Types 
PHP Constants 
PHP Operators 
PHP If...Else...Elseif 
PHP Switch 
PHP While Loops 
PHP For Loops 
3
What is PHP? 
 PHP is an acronym for "PHP Hypertext Preprocessor" 
 PHP is a widely-used, open source scripting language 
 PHP scripts are executed on the server 
 PHP costs nothing, it is free to download and use 
4
 PHP files can contain text, HTML, CSS, JavaScript, and PHP code 
 PHP code are executed on the server, and the result is returned to the 
browser as plain HTML 
 PHP files have extension ".php" 
5
<?php 
echo "<h1 align='center'>Welcome to PHP </h1>"; 
?> 
Execute this code and check the “View page source” you will find simple 
following code 
<h1 align='center'>Welcome to PHP </h1> 
6
 PHP can generate dynamic page content 
 PHP can create, open, read, write, delete, 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. 
7
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) 
 PHP is compatible with almost all servers used today (Apache, IIS, etc.) 
 PHP supports 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 
8
The most universally effective PHP tag style is: 
<?php 
// Php Code here 
?> 
If you use this style, you can be positive that your tags will always be 
correctly interpreted. 
9
HTML script tags: 
<script language=“php”> 
// php code here 
</script> 
10
Short or short-open tags look like this: 
<? 
// Php Code here 
?> 
Set the short_open_tag setting in your php.ini file to on. This option must 
be disabled to parse XML with PHP because the same syntax is used for 
XML tags. 
11
ASP-style tags: 
ASP-style tags mimic the tags used by Active Server Pages to delineate 
code blocks. ASP-style tags look like this: 
<% 
// php code here 
%> 
To use ASP-style tags, you will need to set the configuration option in 
your php.ini file. 
12
 A comment in PHP code is a line that is not read/executed as part of the 
program. Its only purpose is to be read by someone who is editing the 
code! 
Comments are useful for: 
 To let others understand what you are doing - Comments let other 
programmers understand what you were doing in each step (if you work 
in a group) 
 To remind yourself what you did - Most programmers have experienced 
coming back to their own work a year or two later and having to re-figure 
out what they did. Comments can remind you of what you were thinking 
when you wrote the code 
13
PHP supports two types of comments 
 Single line comment 
// This is a single line comment 
# This is also a single line comment 
 Multiline comment 
/* this is multiline comment 
this is multiline comment 
*/ 
14
 In PHP, all user-defined functions, classes, and keywords (e.g. if, else, 
while, echo, etc.) are NOT case-sensitive. 
 In the example below, all three echo statements below are legal (and 
equal): 
<?php 
ECHO "Hello World!<br>"; 
echo "Hello World!<br>"; 
EcHo "Hello World!<br>"; 
?> 
15
 However; in PHP, all variables are case-sensitive. 
 In the example below, only the first statement will display the value of 
the $color variable (this is because $color, $COLOR, and $coLOR are 
treated as three different variables): 
<?php 
$color="red"; 
echo "My car is " . $color . "<br>"; 
echo "My house is " . $COLOR . "<br>"; 
echo "My boat is " . $coLOR . "<br>"; 
?> 
16
 Whitespace is the stuff you type that is typically invisible on the screen, 
including spaces, tabs, and carriage returns (end-of-line characters). 
 PHP whitespace insensitive means that it almost never matters how 
many whitespace characters you have in a row. 
 one whitespace character is the same as many such characters 
 For example, each of the following PHP statements that assigns the 
sum of 2 + 2 to the variable $four is equivalent: 
17
$four = 2 + 2; // single spaces 
$four = 2 + 2 ; // spaces and tabs 
$four = 
2+ 
2; // multiple lines 
All are same. It doesn’t matter how many spaces your are providing in a 
statement, it will be considered as a single space. 
18
 Variables are "containers" for storing information 
 PHP variables can be used to hold values (x=5) or expressions (z=x+y). 
 A variable can have a short name (like x and y) or a more descriptive name (age, carname, 
total_volume). 
Rules for PHP variables: 
 A variable starts with the $ sign, followed by the name of the variable 
 A variable name must start with a letter or the underscore character 
 A variable name cannot start with a number 
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) 
 Variable names are case sensitive ($y and $Y are two different variables) 
19
 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. 
20
 PHP has no command for declaring a variable. 
 A variable is created the moment you first assign a value to it: 
<?php 
$txt="Hello world!"; 
$x=5; 
$y=10.5; 
?> 
After the execution of the statements above, the variable txt will hold the 
value Hello world!, the variable x will hold the value 5, and the 
variable y will hold the value 10.5. 
 Note: When you assign a text value to a variable, put quotes around 
the value. 21
 In the example above, notice that we did not have to tell PHP which data 
type the variable is. 
 PHP automatically converts the variable to the correct data type, 
depending on its value. 
 In other languages such as C, C++, and Java, the programmer must 
declare the name and type of the variable before using it. 
22
In PHP there is two basic ways to get output: echo and print. 
There are some differences between echo and print: 
 echo - can output one or more strings 
 print - can only output one string, and returns always 1 
Tip: echo is marginally faster compared to print as echo does not return any value. 
23
 echo is a language construct, and can be used with or without parentheses: echo or 
echo(). 
Display Strings 
 The following example shows how to display different strings with the echo 
command (also notice that the strings can contain HTML markup): 
<?php 
echo "<h2>PHP is fun!</h2>"; 
echo "Hello world!<br>"; 
echo "I'm about to learn PHP!<br>"; 
echo "This", " string", " was", " made", " with multiple parameters."; 
?> 
24
Display Variables 
 The following example shows how to display strings and variables with 
the echo command: 
 <?php 
$txt1="Learn PHP"; 
$txt2="W3Schools.com"; 
$cars=array("Volvo","BMW","Toyota"); 
echo $txt1; 
echo "<br>"; 
echo "Study PHP at $txt2"; 
echo "<br>"; 
echo "My car is a {$cars[0]}"; 
?> 25
 print is also a language construct, and can be used with or without parentheses: print 
or print(). 
Display Strings 
 The following example shows how to display different strings with the print command 
(also notice that the strings can contain HTML markup): 
<?php 
print "<h2>PHP is fun!</h2>"; 
print "Hello world!<br>"; 
print "I'm about to learn PHP!"; 
?> 
26
Display Variables 
 The following example shows how to display strings and variables with the print 
command: 
<?php 
$txt1="Learn PHP"; 
$txt2="W3Schools.com"; 
$cars=array("Volvo","BMW","Toyota"); 
print $txt1; 
print "<br>"; 
print "Study PHP at $txt2"; 
print "<br>"; 
print "My car is a {$cars[0]}"; 
?> 
27
Scope can be defined as the range of availability a variable has to the 
program in which it is declared. PHP variables can be one of four scope 
types: 
 Local variables 
 Function parameters 
 Global variables 
 Static variables 
28
 A variable declared in a function is considered local; that is, it can be 
referenced solely in that function. Any assignment outside of that 
function will be considered to be an entirely different variable from the 
one contained in the function: 
29
<? 
$x = 4; 
function assignx () { 
$x = 0; 
print "$x inside function is $x. "; 
} 
assignx(); 
print "$x outside of function is $x. "; 
?> 
30
 In contrast to local variables, a global variable can be accessed in any 
part of the program. However, in order to be modified, a global variable 
must be explicitly declared to be global in the function in which it is to 
be modified. This is accomplished, conveniently enough, by placing the 
keyword GLOBAL in front of the variable that should be recognized as 
global. Placing this keyword in front of an already existing variable tells 
PHP to use the variable having that name. Consider an example: 
31
<? 
$somevar = 15; 
function addit() { 
GLOBAL $somevar; 
$somevar++; 
print "Somevar is $somevar"; 
} 
addit(); 
?> 
32
 The final type of variable scoping that I discuss is known as static. In 
contrast to the variables declared as function parameters, which are 
destroyed on the function's exit, a static variable will not lose its value 
when the function exits and will still hold that value should the function 
be called again. 
 You can declare a variable to be static simply by placing the keyword 
STATIC in front of the variable name. 
33
<? 
function keep_track() { 
STATIC $count = 0; 
$count++; 
print $count; 
print “ "; 
} 
keep_track(); 
keep_track(); 
keep_track(); 
?> 
34
 Function parameters are declared after the function name and inside 
parentheses. They are declared much like a typical variable would be: 
<? 
// multiply a value by 10 and return it to the caller 
function multiply ($value) { 
$value = $value * 10; 
return $value; 
} 
$retval = multiply (10); 
Print "Return value is $retvaln"; 
?> 35
PHP has a total of eight data types which we use to construct our variables: 
1. Integers: are whole numbers, without a decimal point, like 4195. 
2. Doubles: are floating-point numbers, like 3.14159 or 49.1. 
3. Booleans: have only two possible values either true or false. 
4. NULL: is a special type that only has one value: NULL. 
5. Strings: are sequences of characters, like 'PHP supports string operations.' 
6. Arrays: are named and indexed collections of other values. 
7. Objects: are instances of programmer-defined classes, which can package up both other kinds of values and 
functions that are specific to the class. 
8. 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. 
36
 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. 
37
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<br>.); 
It produces the following browser output: 
2.28888 + 2.21112 = 4.5 
38
Booleans can be either TRUE or FALSE. 
$x=true; 
$y=false; 
Booleans are often used in conditional testing. 
if (TRUE) 
print("This will always print<br>"); 
else 
print("This will never print<br>"); 
39
 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. 
40
 A string is a sequence of characters, like "Hello world!". 
 A string can be any text inside quotes. You can use single or double quotes: 
<?php 
$x = "Hello world!"; 
echo $x; 
echo "<br>"; 
$x = 'Hello 12BS(CS)'; 
echo $x; 
 ?> 
41
<? 
$variable = "name"; 
$literally = 'My $variable will not print!n'; 
print($literally); 
$literally = "My $variable will print!n"; 
print($literally); 
?> 
42
 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 () 
43
 An array stores multiple values in one single variable. 
In the following example we create an array. 
<?php 
$cars=array("Volvo","BMW","Toyota"); 
echo $car[0]; 
echo $car[1]; 
echo $car[2]; 
?> 
44
 Constants are like variables except that once they are defined they 
cannot be changed or undefined. 
 A constant is an identifier (name) for a simple value. The value 
cannot be changed during the script. 
 A valid constant name starts with a letter or underscore (no $ sign 
before the constant name). 
 Note: Unlike variables, constants are automatically global across the 
entire script. 
45
 To set a constant, use the define() function - it takes three parameters: 
1. The first parameter defines the name of the constant, 
2. the second parameter defines the value of the constant, 
3. the optional third parameter specifies whether the constant name 
should be case-insensitive. Default is false. 
46
The example below creates a case-sensitive constant, with the value of 
"Welcome to W3Schools.com!": 
<?php 
define("GREETING", "Welcome to W3Schools.com!"); 
echo GREETING; 
?> 
The example below creates a case-insensitive constant, with the value of 
"Welcome to W3Schools.com!": 
<?php 
define("GREETING", "Welcome to W3Schools.com!", true); 
echo greeting; 
?> 
47
There is no need to write a dollar sign ($) before a constant, 
where as in Variable one has to write a dollar sign. 
Constants cannot be defined by simple assignment, they 
may only be defined using the define() function. 
Constants may be defined and accessed anywhere without 
regard to variable scoping rules. 
Once the Constants have been set, may not be redefined or 
undefined. 
48
49
PHP Arithmetic Operators 
50 
Operator Name Example Result 
+ Addition $x + $y Sum of $x and $y 
- Subtraction $x - $y Difference of $x and $y 
* Multiplication $x * $y Product of $x and $y 
/ Division $x / $y Quotient of $x and $y 
% Modulus $x % $y Remainder of $x divided by $y
<?php 
$x=10; 
$y=6; 
echo ($x + $y); // outputs 16 
echo ($x - $y); // outputs 4 
echo ($x * $y); // outputs 60 
echo ($x / $y); // outputs 1.6666666666667 
echo ($x % $y); // outputs 4 
?> 
51
 The PHP assignment operators is used to write a value to a variable. 
 The basic assignment operator in PHP is "=". It means that the left 
operand gets set to the value of the assignment expression on the right. 
52 
Assignment Same as... Description 
x = y x = y The left operand gets set to the value of the expression on the 
right 
x += y x = x + y Addition 
x -= y x = x - y Subtraction 
x *= y x = x * y Multiplication 
x /= y x = x / y Division 
x %= y x = x % y Modulus
 <?php 
$x=10; 
echo $x; // outputs 10 
$y=20; 
$y += 100; 
echo $y; // outputs 120 
$z=50; 
$z -= 25; 
echo $z; // outputs 25 
 $i=5; 
$i *= 6; 
echo $i; // outputs 30 
$j=10; 
$j /= 5; 
echo $j; // outputs 2 
$k=15; 
$k %= 4; 
echo $k; // outputs 3 
?> 
53
Operator Name Example Result 
. Concatenation $txt1 = "Hello" 
$txt2 = $txt1 . " world!" 
Now $txt2 contains "Hello 
world!" 
.= Concatenation 
assignment 
$txt1 = "Hello" 
$txt1 .= " world!" 
Now $txt1 contains "Hello 
world!" 
54
55 
<?php 
$a = "Hello"; 
$b = $a . " world!"; 
echo $b; // outputs Hello world! 
$x="Hello"; 
$x .= " world!"; 
echo $x; // outputs Hello world! 
?>
Operator Name Description 
++$x Pre-increment Increments $x by one, then returns $x 
$x++ Post-increment Returns $x, then increments $x by one 
--$x Pre-decrement Decrements $x by one, then returns $x 
$x-- Post-decrement Returns $x, then decrements $x by one 
56
57 
<?php 
$x=10; 
echo ++$x; // outputs 11 
$y=10; 
echo $y++; // outputs 10 
$z=5; 
echo --$z; // outputs 4 
$i=5; 
echo $i--; // outputs 5 
?>
 The PHP comparison operators are used to compare two values (number or string): 
58 
Operator Name Example Result 
== Equal $x == $y True if $x is equal to $y 
=== Identical $x === $y True if $x is equal to $y, and they are of the 
same type 
!= Not equal $x != $y True if $x is not equal to $y 
<> Not equal $x <> $y True if $x is not equal to $y 
!== Not identical $x !== $y True if $x is not equal to $y, or they are not of 
the same type 
> Greater than $x > $y True if $x is greater than $y 
< Less than $x < $y True if $x is less than $y 
>= Greater than or equal to $x >= $y True if $x is greater than or equal to $y 
<= Less than or equal to $x <= $y True if $x is less than or equal to $y
Operator Name Example Result 
and And $x and $y True if both $x and $y are true 
or Or $x or $y True if either $x or $y is true 
xor Xor $x xor $y True if either $x or $y is true, but not both 
&& And $x && $y True if both $x and $y are true 
|| Or $x || $y True if either $x or $y is true 
! Not !$x True if $x is not true 
59
 The PHP array operators are used to compare arrays: 
60 
Operator Name Example Result 
+ Union $x + $y Union of $x and $y (but duplicate keys are 
not overwritten) 
== Equality $x == $y True if $x and $y have the same key/value 
pairs 
=== Identity $x === $y True if $x and $y have the same key/value 
pairs in the same order and of the same 
types 
!= Inequality $x != $y True if $x is not equal to $y 
<> Inequality $x <> $y True if $x is not equal to $y 
!== Non-identity $x !== $y True if $x is not identical to $y
 Conditional statements are used to perform different actions based on different 
conditions. 
 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: 
1. if statement - executes some code only if a specified condition is true 
2. if...else statement - executes some code if a condition is true and another code if 
the condition is false 
3. if...elseif....else statement - selects one of several blocks of code to be executed 
4. switch statement - selects one of many blocks of code to be executed 
61
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; 
} 
<?php 
$t=date("H"); 
if ($t<"20") 
{ 
echo "Have a good day!"; 
} 
?> 
62
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; 
} 
63
<?php 
$t=date("H"); 
if ($t<"20") 
{ 
echo "Have a good day!"; 
} 
else 
{ 
echo "Have a good night!"; 
} 
?> 
64
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; 
} 
65
<?php 
$t=date("H"); 
if ($t<"10") 
{ 
echo "Have a good 
morning!"; 
} 
elseif ($t<"20") 
{ 
echo "Have a good day!"; 
} 
else 
{ 
echo "Have a good night!"; 
} 
?> 
66
 The switch statement is used to perform different actions based on 
different conditions. 
 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; 
case label3: code to be executed if n=label3; break; 
... 
default: code to be executed if n is different from all labels; 
} 67
 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. 
68
<?php 
$d=date("D"); 
switch ($d) 
{ 
case "Mon": echo "Today is Monday"; break; 
case "Tue": echo "Today is Tuesday"; break; 
case "Wed": echo "Today is Wednesday"; break; 
case "Thu": echo "Today is Thursday"; break; 
case "Fri": echo "Today is Friday"; break; 
case "Sat": echo "Today is Saturday"; break; 
case "Sun": echo "Today is Sunday"; break; 
default: echo "Wonder which day is this ?"; 
} 
?> 69
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 code-lines in 
a script, we can use loops to perform a task like this. 
In PHP, we have the following looping statements: 
1.while - loops through a block of code as long as the specified condition 
is true 
2.do...while - loops through a block of code once, and then repeats the 
loop as long as the specified condition is true 
3.for - loops through a block of code a specified number of times 
4.foreach - loops through a block of code for each element in an array 
70
The while loop executes a block of code as long as the specified 
condition is true. 
Syntax 
while (condition is true) 
{ 
code to be executed; 
} 
71
The example below first sets a variable $x to 1 ($x=1;). Then, the while 
loop will continue to run as long as $x is less than, or equal to 5. $x will 
increase by 1 each time the loop runs ($x++;): 
Example 
<?php 
$x=1; 
while($x<=5) 
{ 
echo "The number is: $x <br>"; 
$x++; 
} 
?> 
72
The do...while loop will always execute the block of code once, it will 
then check the condition, and repeat the loop while the specified 
condition is true. 
Syntax 
do 
{ 
code to be executed; 
} 
while (condition is true); 
73
The example below first sets a variable $x to 1 ($x=1;). Then, the do while 
loop will write some output, and then increment the variable $x with 1. Then 
the condition is checked (is $x less than, or equal to 5?), and the loop will 
continue to run as long as $x is less than, or equal to 5: 
Example 
<?php 
$x=1; 
do 
{ 
echo "The number is: $x <br>"; 
$x++; 
} 
while ($x<=5) 
?> 
74
 Notice that in a do while loop the condition is tested AFTER executing the 
statements within the loop. This means that the do while loop would execute its 
statements at least once, even if the condition fails the first time. 
 The example below sets the $x variable to 6, then it runs the loop, and then the 
condition is checked: 
<?php 
$x=6; 
do 
{ 
echo "The number is: $x <br>"; 
$x++; 
} 
while ($x<=5) 
?> 
75
The for loop is used when you know in advance how many times the 
script should run. 
Syntax 
for (init counter; test counter; increment counter) 
{ 
code to be executed; 
} 
76
Parameters: 
 init counter: Initialize the loop counter value 
 test counter: Evaluated for each loop iteration. If it evaluates to TRUE, 
the loop continues. If it evaluates to FALSE, the loop ends. 
 increment counter: Increases the loop counter value 
77
The example below displays the numbers from 0 to 10: 
Example 
<?php 
for ($x=0; $x<=10; $x++) 
{ 
echo "The number is: $x <br>"; 
} 
?> 
78
The foreach loop works only on arrays, and is used to loop through each 
key/value pair in an array. 
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, until it reaches the last array 
element. 
79
The following example demonstrates a loop that will output the values of the 
given array ($colors): 
Example 
<?php 
$colors = array("red","green","blue","yellow"); 
foreach ($colors as $value) 
{ 
echo "$value <br>"; 
} 
?> 
80
 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. 
81
 In the following example condition test becomes true when the counter value reaches 3 
and loop terminates. 
<?php 
$i = 0; 
while( $i < 10) 
{ 
$i++; 
if( $i == 3 )break; 
} 
echo ("Loop stopped at i = $i" ); 
?> 
82
 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 block 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. 
83
Example 
 In the following example loop prints the value of array but for which condition 
becomes true it just skip the code and next value is printed. 
<?php 
$array = array( 1, 2, 3, 4, 5); 
foreach( $array as $value ) 
{ 
if( $value == 3 )continue; 
echo "Value is $value <br />"; 
} 
?> 
84
 The real power of PHP comes from its functions; it has more than 1000 built-in 
functions. 
PHP User Defined Functions 
 Besides the built-in PHP functions, we can create our own functions. 
 A function is a block of statements that can be used repeatedly in a program. 
 A function will not execute immediately when a page loads. 
 A function will be executed by a call to the function. 
 
85
A user defined function declaration starts with the word "function": 
Syntax 
function functionName() 
{ 
code to be executed; 
} 
Note: A function name can start with a letter or underscore (not a 
number). 
Tip: Give the function a name that reflects what the function does! 
86
 In the example below, we create a function named "writeMsg()". The 
opening curly brace ( { ) indicates the beginning of the function code 
and the closing curly brace ( } ) indicates the end of the function. The 
function outputs "Hello world!". To call the function, just write its name: 
<?php 
function writeMsg() 
{ 
echo "Hello world!"; 
} 
writeMsg(); // call the function 
?> 
87
 Information can be passed to functions through arguments. An argument is just like a variable. 
 Arguments are specified after the function name, inside the parentheses. You can add as many 
arguments as you want, just seperate them with a comma. 
<?php 
function addFunction($num1, $num2) 
{ 
$sum = $num1 + $num2; 
echo "Sum of the two numbers is : $sum"; 
} 
addFunction(10, 20); 
?> 
88
 A function can return a value using the return statement in conjunction 
with a value or object. return stops the execution of the function and 
sends the value back to the calling code. 
 You can return more than one value from a function using return 
array(1,2,3,4). 
 Following example takes two integer parameters and add them 
together and then returns their sum to the calling program. Note 
that return keyword is used to return a value from a function. 
89
<?php 
function addFunction($num1, $num2) 
{ 
$sum = $num1 + $num2; 
return $sum; 
} 
$return_value = addFunction(10, 20); 
echo "Returned value from the function : $return_value"; 
?> 
90
<?php 
function table($a = 12) 
{ 
for($i=1; $i<10; $i++) 
{ 
echo " $a * $i = $a*$i <br />" ; 
} 
} 
table(); 
table(3); 
?> 
91
 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. 
92
<?php 
function addFive($num) 
{ 
$num += 5; 
} 
function addSix(&$num) 
{ 
$num += 6; 
} 
$orignum = 10; 
addFive($orignum ); 
echo "Original Value is $orignum<br />"; 
addSix( $orignum ); 
echo "Original Value is $orignum<br />"; 
?> 
93
What is an Array? 
 An array stores multiple values in one single variable: 
 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! 
94
 An array can hold many values under a single name, and you can access the values 
by referring to an index number. 
Create an Array in PHP 
In PHP, the array() function is used to create an array: 
 array(); 
In PHP, there are three types of arrays: 
1.Indexed arrays - Arrays with numeric index 
2.Associative arrays - Arrays with named keys 
3.Multidimensional arrays - Arrays containing one or more arrays 
95
There are two ways to create indexed arrays: 
The index can be assigned automatically (index always starts at 0): 
$cars=array("Volvo","BMW","Toyota"); 
 or the index can be assigned manually: 
$cars[0]="Volvo"; 
$cars[1]="BMW"; 
$cars[2]="Toyota"; 
96
 The following example creates an indexed array named $cars, assigns 
three elements to it, and then prints a text containing the array values: 
Example 
 <?php 
$cars=array("Volvo","BMW","Toyota"); 
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; 
?> 
97
The count() function is used to return the length (the number 
of elements) of an array: 
Example 
<?php 
$cars=array("Volvo","BMW","Toyota"); 
echo count($cars); 
?> 
98
To loop through and print all the values of an indexed array, you could 
use a for loop, like this: 
Example 
<?php 
$cars=array("Volvo","BMW","Toyota"); 
$arrlength=count($cars); 
for($x=0; $x<$arrlength; $x++) 
{ 
echo $cars[$x]; 
echo "<br>"; 
} 
?> 99
Associative arrays are arrays that use named keys that you assign to them. 
There are two ways to create an associative array: 
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); 
or: 
$age['Peter']="35"; 
$age['Ben']="37"; 
$age['Joe']="43"; 
The named keys can then be used in a script: 
Example 
<?php 
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); 
echo "Peter is " . $age['Peter'] . " years old."; 
?> 
100
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 
 <?php 
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); 
foreach($age as $x=>$x_value) 
{ 
echo "Key=" . $x . ", Value=" . $x_value; 
echo "<br>"; 
} 
?> 
101
 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. 
102
$marks = array( 
"mohammad" => array 
( 
"physics" => 35, 
"maths" => 30, 
"chemistry" => 39 
), 
" Zara" => array 
( 
"physics" => 31, 
"maths" => 22, 
"chemistry" => 39 
) ); 
103
/* Accessing multi-dimensional array values */ 
echo "Marks for mohammad in physics : " ; 
echo $marks['mohammad']['physics'] . "<br />"; 
echo "Marks for zara in chemistry : " ; 
echo $marks['zara']['chemistry'] . "<br />"; 
104
 http://www.w3schools.com/php/ 
 http://www.tutorialspoint.com/php/php_introduction.htm 
105

Contenu connexe

Tendances

Tendances (20)

Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
 
Chap 4 PHP.pdf
Chap 4 PHP.pdfChap 4 PHP.pdf
Chap 4 PHP.pdf
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 
Jquery
JqueryJquery
Jquery
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 
PHP filter
PHP filterPHP filter
PHP filter
 
Java script
Java scriptJava script
Java script
 
PHP
PHPPHP
PHP
 
Php
PhpPhp
Php
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
 
PHP Loops and PHP Forms
PHP  Loops and PHP FormsPHP  Loops and PHP Forms
PHP Loops and PHP Forms
 
Html form tag
Html form tagHtml form tag
Html form tag
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
Html5-Web-Storage
Html5-Web-StorageHtml5-Web-Storage
Html5-Web-Storage
 
Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to JSON
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 

En vedette

En vedette (20)

Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)
 
PHP HTML CSS Notes
PHP HTML CSS  NotesPHP HTML CSS  Notes
PHP HTML CSS Notes
 
php tutorial - By Bally Chohan
php tutorial - By Bally Chohanphp tutorial - By Bally Chohan
php tutorial - By Bally Chohan
 
Web app development_cookies_sessions_14
Web app development_cookies_sessions_14Web app development_cookies_sessions_14
Web app development_cookies_sessions_14
 
Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3
 
安全なPHPアプリケーションの作り方2013
安全なPHPアプリケーションの作り方2013安全なPHPアプリケーションの作り方2013
安全なPHPアプリケーションの作り方2013
 
Javascript Question
Javascript QuestionJavascript Question
Javascript Question
 
3 jenis pengalaman
3 jenis pengalaman3 jenis pengalaman
3 jenis pengalaman
 
Pk std
Pk stdPk std
Pk std
 
Lift hero class1_presentation
Lift hero class1_presentationLift hero class1_presentation
Lift hero class1_presentation
 
CAMPUSMATE
CAMPUSMATECAMPUSMATE
CAMPUSMATE
 
Kjdf
KjdfKjdf
Kjdf
 
Ciclo basico diurno vigencia 2009 scp
Ciclo basico diurno vigencia 2009 scpCiclo basico diurno vigencia 2009 scp
Ciclo basico diurno vigencia 2009 scp
 
Celevation
CelevationCelevation
Celevation
 
By Phasse - Catalogue-ing
By Phasse - Catalogue-ingBy Phasse - Catalogue-ing
By Phasse - Catalogue-ing
 
Jst part1
Jst part1Jst part1
Jst part1
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with Wings
 
SIGEVOlution Spring 2007
SIGEVOlution Spring 2007SIGEVOlution Spring 2007
SIGEVOlution Spring 2007
 

Similaire à Basic of PHP

1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_masterjeeva indra
 
Php tutorial from_beginner_to_master
Php tutorial from_beginner_to_masterPhp tutorial from_beginner_to_master
Php tutorial from_beginner_to_masterPrinceGuru MS
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPwahidullah mudaser
 
Php web development
Php web developmentPhp web development
Php web developmentRamesh Gupta
 
PHP Training Part1
PHP Training Part1PHP Training Part1
PHP Training Part1than sare
 
PHP Comprehensive Overview
PHP Comprehensive OverviewPHP Comprehensive Overview
PHP Comprehensive OverviewMohamed Loey
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Gheyath M. Othman
 
Php by shivitomer
Php by shivitomerPhp by shivitomer
Php by shivitomerShivi Tomer
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)Arjun Shanka
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQLArti Parab Academics
 
Introduction to PHP.ppt
Introduction to PHP.pptIntroduction to PHP.ppt
Introduction to PHP.pptSanthiNivas
 

Similaire à Basic of PHP (20)

PHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERSPHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERS
 
1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master
 
Php tutorial from_beginner_to_master
Php tutorial from_beginner_to_masterPhp tutorial from_beginner_to_master
Php tutorial from_beginner_to_master
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
Php web development
Php web developmentPhp web development
Php web development
 
Lesson 1 php syntax
Lesson 1   php syntaxLesson 1   php syntax
Lesson 1 php syntax
 
Materi Dasar PHP
Materi Dasar PHPMateri Dasar PHP
Materi Dasar PHP
 
Php
PhpPhp
Php
 
PHP
PHPPHP
PHP
 
PHP Basic & Variables
PHP Basic & VariablesPHP Basic & Variables
PHP Basic & Variables
 
PHP Training Part1
PHP Training Part1PHP Training Part1
PHP Training Part1
 
PHP Comprehensive Overview
PHP Comprehensive OverviewPHP Comprehensive Overview
PHP Comprehensive Overview
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
 
Php by shivitomer
Php by shivitomerPhp by shivitomer
Php by shivitomer
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Php tutorialw3schools
Php tutorialw3schoolsPhp tutorialw3schools
Php tutorialw3schools
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
Php essentials
Php essentialsPhp essentials
Php essentials
 
Introduction to PHP.ppt
Introduction to PHP.pptIntroduction to PHP.ppt
Introduction to PHP.ppt
 

Plus de Nisa Soomro

Plus de Nisa Soomro (16)

PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
Connecting to my sql using PHP
Connecting to my sql using PHPConnecting to my sql using PHP
Connecting to my sql using PHP
 
PHP Filing
PHP Filing PHP Filing
PHP Filing
 
Html5
Html5Html5
Html5
 
HTML Basic Tags
HTML Basic Tags HTML Basic Tags
HTML Basic Tags
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
 
HTML Frameset & Inline Frame
HTML Frameset & Inline FrameHTML Frameset & Inline Frame
HTML Frameset & Inline Frame
 
HTML Images
HTML Images HTML Images
HTML Images
 
HTML Lists & Llinks
HTML Lists & LlinksHTML Lists & Llinks
HTML Lists & Llinks
 
HTML Tables
HTML TablesHTML Tables
HTML Tables
 
Html5 SVG
Html5 SVGHtml5 SVG
Html5 SVG
 
Html5 Canvas Detail
Html5 Canvas DetailHtml5 Canvas Detail
Html5 Canvas Detail
 
Html5 canvas
Html5 canvasHtml5 canvas
Html5 canvas
 
Html5
Html5Html5
Html5
 
Html
HtmlHtml
Html
 
Web programming lec#3
Web programming lec#3Web programming lec#3
Web programming lec#3
 

Dernier

Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 

Dernier (20)

Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 

Basic of PHP

  • 2.  PHP and MySQL Web Development Fourth Edition “Luke Welling, Laura Thomson”  http://sage.math.washington.edu/home/wstein/www/home/agc/lit/php/PHPMySQL.pdf  www.W3school.com 2
  • 3. PHP Intro PHP Install PHP Syntax PHP Variables PHP Echo / Print PHP Data Types PHP Constants PHP Operators PHP If...Else...Elseif PHP Switch PHP While Loops PHP For Loops 3
  • 4. What is PHP?  PHP is an acronym for "PHP Hypertext Preprocessor"  PHP is a widely-used, open source scripting language  PHP scripts are executed on the server  PHP costs nothing, it is free to download and use 4
  • 5.  PHP files can contain text, HTML, CSS, JavaScript, and PHP code  PHP code are executed on the server, and the result is returned to the browser as plain HTML  PHP files have extension ".php" 5
  • 6. <?php echo "<h1 align='center'>Welcome to PHP </h1>"; ?> Execute this code and check the “View page source” you will find simple following code <h1 align='center'>Welcome to PHP </h1> 6
  • 7.  PHP can generate dynamic page content  PHP can create, open, read, write, delete, 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. 7
  • 8.  PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)  PHP is compatible with almost all servers used today (Apache, IIS, etc.)  PHP supports 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 8
  • 9. The most universally effective PHP tag style is: <?php // Php Code here ?> If you use this style, you can be positive that your tags will always be correctly interpreted. 9
  • 10. HTML script tags: <script language=“php”> // php code here </script> 10
  • 11. Short or short-open tags look like this: <? // Php Code here ?> Set the short_open_tag setting in your php.ini file to on. This option must be disabled to parse XML with PHP because the same syntax is used for XML tags. 11
  • 12. ASP-style tags: ASP-style tags mimic the tags used by Active Server Pages to delineate code blocks. ASP-style tags look like this: <% // php code here %> To use ASP-style tags, you will need to set the configuration option in your php.ini file. 12
  • 13.  A comment in PHP code is a line that is not read/executed as part of the program. Its only purpose is to be read by someone who is editing the code! Comments are useful for:  To let others understand what you are doing - Comments let other programmers understand what you were doing in each step (if you work in a group)  To remind yourself what you did - Most programmers have experienced coming back to their own work a year or two later and having to re-figure out what they did. Comments can remind you of what you were thinking when you wrote the code 13
  • 14. PHP supports two types of comments  Single line comment // This is a single line comment # This is also a single line comment  Multiline comment /* this is multiline comment this is multiline comment */ 14
  • 15.  In PHP, all user-defined functions, classes, and keywords (e.g. if, else, while, echo, etc.) are NOT case-sensitive.  In the example below, all three echo statements below are legal (and equal): <?php ECHO "Hello World!<br>"; echo "Hello World!<br>"; EcHo "Hello World!<br>"; ?> 15
  • 16.  However; in PHP, all variables are case-sensitive.  In the example below, only the first statement will display the value of the $color variable (this is because $color, $COLOR, and $coLOR are treated as three different variables): <?php $color="red"; echo "My car is " . $color . "<br>"; echo "My house is " . $COLOR . "<br>"; echo "My boat is " . $coLOR . "<br>"; ?> 16
  • 17.  Whitespace is the stuff you type that is typically invisible on the screen, including spaces, tabs, and carriage returns (end-of-line characters).  PHP whitespace insensitive means that it almost never matters how many whitespace characters you have in a row.  one whitespace character is the same as many such characters  For example, each of the following PHP statements that assigns the sum of 2 + 2 to the variable $four is equivalent: 17
  • 18. $four = 2 + 2; // single spaces $four = 2 + 2 ; // spaces and tabs $four = 2+ 2; // multiple lines All are same. It doesn’t matter how many spaces your are providing in a statement, it will be considered as a single space. 18
  • 19.  Variables are "containers" for storing information  PHP variables can be used to hold values (x=5) or expressions (z=x+y).  A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for PHP variables:  A variable starts with the $ sign, followed by the name of the variable  A variable name must start with a letter or the underscore character  A variable name cannot start with a number  A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )  Variable names are case sensitive ($y and $Y are two different variables) 19
  • 20.  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. 20
  • 21.  PHP has no command for declaring a variable.  A variable is created the moment you first assign a value to it: <?php $txt="Hello world!"; $x=5; $y=10.5; ?> After the execution of the statements above, the variable txt will hold the value Hello world!, the variable x will hold the value 5, and the variable y will hold the value 10.5.  Note: When you assign a text value to a variable, put quotes around the value. 21
  • 22.  In the example above, notice that we did not have to tell PHP which data type the variable is.  PHP automatically converts the variable to the correct data type, depending on its value.  In other languages such as C, C++, and Java, the programmer must declare the name and type of the variable before using it. 22
  • 23. In PHP there is two basic ways to get output: echo and print. There are some differences between echo and print:  echo - can output one or more strings  print - can only output one string, and returns always 1 Tip: echo is marginally faster compared to print as echo does not return any value. 23
  • 24.  echo is a language construct, and can be used with or without parentheses: echo or echo(). Display Strings  The following example shows how to display different strings with the echo command (also notice that the strings can contain HTML markup): <?php echo "<h2>PHP is fun!</h2>"; echo "Hello world!<br>"; echo "I'm about to learn PHP!<br>"; echo "This", " string", " was", " made", " with multiple parameters."; ?> 24
  • 25. Display Variables  The following example shows how to display strings and variables with the echo command:  <?php $txt1="Learn PHP"; $txt2="W3Schools.com"; $cars=array("Volvo","BMW","Toyota"); echo $txt1; echo "<br>"; echo "Study PHP at $txt2"; echo "<br>"; echo "My car is a {$cars[0]}"; ?> 25
  • 26.  print is also a language construct, and can be used with or without parentheses: print or print(). Display Strings  The following example shows how to display different strings with the print command (also notice that the strings can contain HTML markup): <?php print "<h2>PHP is fun!</h2>"; print "Hello world!<br>"; print "I'm about to learn PHP!"; ?> 26
  • 27. Display Variables  The following example shows how to display strings and variables with the print command: <?php $txt1="Learn PHP"; $txt2="W3Schools.com"; $cars=array("Volvo","BMW","Toyota"); print $txt1; print "<br>"; print "Study PHP at $txt2"; print "<br>"; print "My car is a {$cars[0]}"; ?> 27
  • 28. Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types:  Local variables  Function parameters  Global variables  Static variables 28
  • 29.  A variable declared in a function is considered local; that is, it can be referenced solely in that function. Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function: 29
  • 30. <? $x = 4; function assignx () { $x = 0; print "$x inside function is $x. "; } assignx(); print "$x outside of function is $x. "; ?> 30
  • 31.  In contrast to local variables, a global variable can be accessed in any part of the program. However, in order to be modified, a global variable must be explicitly declared to be global in the function in which it is to be modified. This is accomplished, conveniently enough, by placing the keyword GLOBAL in front of the variable that should be recognized as global. Placing this keyword in front of an already existing variable tells PHP to use the variable having that name. Consider an example: 31
  • 32. <? $somevar = 15; function addit() { GLOBAL $somevar; $somevar++; print "Somevar is $somevar"; } addit(); ?> 32
  • 33.  The final type of variable scoping that I discuss is known as static. In contrast to the variables declared as function parameters, which are destroyed on the function's exit, a static variable will not lose its value when the function exits and will still hold that value should the function be called again.  You can declare a variable to be static simply by placing the keyword STATIC in front of the variable name. 33
  • 34. <? function keep_track() { STATIC $count = 0; $count++; print $count; print “ "; } keep_track(); keep_track(); keep_track(); ?> 34
  • 35.  Function parameters are declared after the function name and inside parentheses. They are declared much like a typical variable would be: <? // multiply a value by 10 and return it to the caller function multiply ($value) { $value = $value * 10; return $value; } $retval = multiply (10); Print "Return value is $retvaln"; ?> 35
  • 36. PHP has a total of eight data types which we use to construct our variables: 1. Integers: are whole numbers, without a decimal point, like 4195. 2. Doubles: are floating-point numbers, like 3.14159 or 49.1. 3. Booleans: have only two possible values either true or false. 4. NULL: is a special type that only has one value: NULL. 5. Strings: are sequences of characters, like 'PHP supports string operations.' 6. Arrays: are named and indexed collections of other values. 7. Objects: are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class. 8. 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. 36
  • 37.  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. 37
  • 38. 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<br>.); It produces the following browser output: 2.28888 + 2.21112 = 4.5 38
  • 39. Booleans can be either TRUE or FALSE. $x=true; $y=false; Booleans are often used in conditional testing. if (TRUE) print("This will always print<br>"); else print("This will never print<br>"); 39
  • 40.  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. 40
  • 41.  A string is a sequence of characters, like "Hello world!".  A string can be any text inside quotes. You can use single or double quotes: <?php $x = "Hello world!"; echo $x; echo "<br>"; $x = 'Hello 12BS(CS)'; echo $x;  ?> 41
  • 42. <? $variable = "name"; $literally = 'My $variable will not print!n'; print($literally); $literally = "My $variable will print!n"; print($literally); ?> 42
  • 43.  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 () 43
  • 44.  An array stores multiple values in one single variable. In the following example we create an array. <?php $cars=array("Volvo","BMW","Toyota"); echo $car[0]; echo $car[1]; echo $car[2]; ?> 44
  • 45.  Constants are like variables except that once they are defined they cannot be changed or undefined.  A constant is an identifier (name) for a simple value. The value cannot be changed during the script.  A valid constant name starts with a letter or underscore (no $ sign before the constant name).  Note: Unlike variables, constants are automatically global across the entire script. 45
  • 46.  To set a constant, use the define() function - it takes three parameters: 1. The first parameter defines the name of the constant, 2. the second parameter defines the value of the constant, 3. the optional third parameter specifies whether the constant name should be case-insensitive. Default is false. 46
  • 47. The example below creates a case-sensitive constant, with the value of "Welcome to W3Schools.com!": <?php define("GREETING", "Welcome to W3Schools.com!"); echo GREETING; ?> The example below creates a case-insensitive constant, with the value of "Welcome to W3Schools.com!": <?php define("GREETING", "Welcome to W3Schools.com!", true); echo greeting; ?> 47
  • 48. There is no need to write a dollar sign ($) before a constant, where as in Variable one has to write a dollar sign. Constants cannot be defined by simple assignment, they may only be defined using the define() function. Constants may be defined and accessed anywhere without regard to variable scoping rules. Once the Constants have been set, may not be redefined or undefined. 48
  • 49. 49
  • 50. PHP Arithmetic Operators 50 Operator Name Example Result + Addition $x + $y Sum of $x and $y - Subtraction $x - $y Difference of $x and $y * Multiplication $x * $y Product of $x and $y / Division $x / $y Quotient of $x and $y % Modulus $x % $y Remainder of $x divided by $y
  • 51. <?php $x=10; $y=6; echo ($x + $y); // outputs 16 echo ($x - $y); // outputs 4 echo ($x * $y); // outputs 60 echo ($x / $y); // outputs 1.6666666666667 echo ($x % $y); // outputs 4 ?> 51
  • 52.  The PHP assignment operators is used to write a value to a variable.  The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right. 52 Assignment Same as... Description x = y x = y The left operand gets set to the value of the expression on the right x += y x = x + y Addition x -= y x = x - y Subtraction x *= y x = x * y Multiplication x /= y x = x / y Division x %= y x = x % y Modulus
  • 53.  <?php $x=10; echo $x; // outputs 10 $y=20; $y += 100; echo $y; // outputs 120 $z=50; $z -= 25; echo $z; // outputs 25  $i=5; $i *= 6; echo $i; // outputs 30 $j=10; $j /= 5; echo $j; // outputs 2 $k=15; $k %= 4; echo $k; // outputs 3 ?> 53
  • 54. Operator Name Example Result . Concatenation $txt1 = "Hello" $txt2 = $txt1 . " world!" Now $txt2 contains "Hello world!" .= Concatenation assignment $txt1 = "Hello" $txt1 .= " world!" Now $txt1 contains "Hello world!" 54
  • 55. 55 <?php $a = "Hello"; $b = $a . " world!"; echo $b; // outputs Hello world! $x="Hello"; $x .= " world!"; echo $x; // outputs Hello world! ?>
  • 56. Operator Name Description ++$x Pre-increment Increments $x by one, then returns $x $x++ Post-increment Returns $x, then increments $x by one --$x Pre-decrement Decrements $x by one, then returns $x $x-- Post-decrement Returns $x, then decrements $x by one 56
  • 57. 57 <?php $x=10; echo ++$x; // outputs 11 $y=10; echo $y++; // outputs 10 $z=5; echo --$z; // outputs 4 $i=5; echo $i--; // outputs 5 ?>
  • 58.  The PHP comparison operators are used to compare two values (number or string): 58 Operator Name Example Result == Equal $x == $y True if $x is equal to $y === Identical $x === $y True if $x is equal to $y, and they are of the same type != Not equal $x != $y True if $x is not equal to $y <> Not equal $x <> $y True if $x is not equal to $y !== Not identical $x !== $y True if $x is not equal to $y, or they are not of the same type > Greater than $x > $y True if $x is greater than $y < Less than $x < $y True if $x is less than $y >= Greater than or equal to $x >= $y True if $x is greater than or equal to $y <= Less than or equal to $x <= $y True if $x is less than or equal to $y
  • 59. Operator Name Example Result and And $x and $y True if both $x and $y are true or Or $x or $y True if either $x or $y is true xor Xor $x xor $y True if either $x or $y is true, but not both && And $x && $y True if both $x and $y are true || Or $x || $y True if either $x or $y is true ! Not !$x True if $x is not true 59
  • 60.  The PHP array operators are used to compare arrays: 60 Operator Name Example Result + Union $x + $y Union of $x and $y (but duplicate keys are not overwritten) == Equality $x == $y True if $x and $y have the same key/value pairs === Identity $x === $y True if $x and $y have the same key/value pairs in the same order and of the same types != Inequality $x != $y True if $x is not equal to $y <> Inequality $x <> $y True if $x is not equal to $y !== Non-identity $x !== $y True if $x is not identical to $y
  • 61.  Conditional statements are used to perform different actions based on different conditions.  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: 1. if statement - executes some code only if a specified condition is true 2. if...else statement - executes some code if a condition is true and another code if the condition is false 3. if...elseif....else statement - selects one of several blocks of code to be executed 4. switch statement - selects one of many blocks of code to be executed 61
  • 62. 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; } <?php $t=date("H"); if ($t<"20") { echo "Have a good day!"; } ?> 62
  • 63. 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; } 63
  • 64. <?php $t=date("H"); if ($t<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?> 64
  • 65. 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; } 65
  • 66. <?php $t=date("H"); if ($t<"10") { echo "Have a good morning!"; } elseif ($t<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?> 66
  • 67.  The switch statement is used to perform different actions based on different conditions.  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; case label3: code to be executed if n=label3; break; ... default: code to be executed if n is different from all labels; } 67
  • 68.  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. 68
  • 69. <?php $d=date("D"); switch ($d) { case "Mon": echo "Today is Monday"; break; case "Tue": echo "Today is Tuesday"; break; case "Wed": echo "Today is Wednesday"; break; case "Thu": echo "Today is Thursday"; break; case "Fri": echo "Today is Friday"; break; case "Sat": echo "Today is Saturday"; break; case "Sun": echo "Today is Sunday"; break; default: echo "Wonder which day is this ?"; } ?> 69
  • 70. 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 code-lines in a script, we can use loops to perform a task like this. In PHP, we have the following looping statements: 1.while - loops through a block of code as long as the specified condition is true 2.do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true 3.for - loops through a block of code a specified number of times 4.foreach - loops through a block of code for each element in an array 70
  • 71. The while loop executes a block of code as long as the specified condition is true. Syntax while (condition is true) { code to be executed; } 71
  • 72. The example below first sets a variable $x to 1 ($x=1;). Then, the while loop will continue to run as long as $x is less than, or equal to 5. $x will increase by 1 each time the loop runs ($x++;): Example <?php $x=1; while($x<=5) { echo "The number is: $x <br>"; $x++; } ?> 72
  • 73. The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true. Syntax do { code to be executed; } while (condition is true); 73
  • 74. The example below first sets a variable $x to 1 ($x=1;). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5: Example <?php $x=1; do { echo "The number is: $x <br>"; $x++; } while ($x<=5) ?> 74
  • 75.  Notice that in a do while loop the condition is tested AFTER executing the statements within the loop. This means that the do while loop would execute its statements at least once, even if the condition fails the first time.  The example below sets the $x variable to 6, then it runs the loop, and then the condition is checked: <?php $x=6; do { echo "The number is: $x <br>"; $x++; } while ($x<=5) ?> 75
  • 76. The for loop is used when you know in advance how many times the script should run. Syntax for (init counter; test counter; increment counter) { code to be executed; } 76
  • 77. Parameters:  init counter: Initialize the loop counter value  test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.  increment counter: Increases the loop counter value 77
  • 78. The example below displays the numbers from 0 to 10: Example <?php for ($x=0; $x<=10; $x++) { echo "The number is: $x <br>"; } ?> 78
  • 79. The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. 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, until it reaches the last array element. 79
  • 80. The following example demonstrates a loop that will output the values of the given array ($colors): Example <?php $colors = array("red","green","blue","yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?> 80
  • 81.  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. 81
  • 82.  In the following example condition test becomes true when the counter value reaches 3 and loop terminates. <?php $i = 0; while( $i < 10) { $i++; if( $i == 3 )break; } echo ("Loop stopped at i = $i" ); ?> 82
  • 83.  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 block 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. 83
  • 84. Example  In the following example loop prints the value of array but for which condition becomes true it just skip the code and next value is printed. <?php $array = array( 1, 2, 3, 4, 5); foreach( $array as $value ) { if( $value == 3 )continue; echo "Value is $value <br />"; } ?> 84
  • 85.  The real power of PHP comes from its functions; it has more than 1000 built-in functions. PHP User Defined Functions  Besides the built-in PHP functions, we can create our own functions.  A function is a block of statements that can be used repeatedly in a program.  A function will not execute immediately when a page loads.  A function will be executed by a call to the function.  85
  • 86. A user defined function declaration starts with the word "function": Syntax function functionName() { code to be executed; } Note: A function name can start with a letter or underscore (not a number). Tip: Give the function a name that reflects what the function does! 86
  • 87.  In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates the beginning of the function code and the closing curly brace ( } ) indicates the end of the function. The function outputs "Hello world!". To call the function, just write its name: <?php function writeMsg() { echo "Hello world!"; } writeMsg(); // call the function ?> 87
  • 88.  Information can be passed to functions through arguments. An argument is just like a variable.  Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just seperate them with a comma. <?php function addFunction($num1, $num2) { $sum = $num1 + $num2; echo "Sum of the two numbers is : $sum"; } addFunction(10, 20); ?> 88
  • 89.  A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.  You can return more than one value from a function using return array(1,2,3,4).  Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function. 89
  • 90. <?php function addFunction($num1, $num2) { $sum = $num1 + $num2; return $sum; } $return_value = addFunction(10, 20); echo "Returned value from the function : $return_value"; ?> 90
  • 91. <?php function table($a = 12) { for($i=1; $i<10; $i++) { echo " $a * $i = $a*$i <br />" ; } } table(); table(3); ?> 91
  • 92.  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. 92
  • 93. <?php function addFive($num) { $num += 5; } function addSix(&$num) { $num += 6; } $orignum = 10; addFive($orignum ); echo "Original Value is $orignum<br />"; addSix( $orignum ); echo "Original Value is $orignum<br />"; ?> 93
  • 94. What is an Array?  An array stores multiple values in one single variable:  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! 94
  • 95.  An array can hold many values under a single name, and you can access the values by referring to an index number. Create an Array in PHP In PHP, the array() function is used to create an array:  array(); In PHP, there are three types of arrays: 1.Indexed arrays - Arrays with numeric index 2.Associative arrays - Arrays with named keys 3.Multidimensional arrays - Arrays containing one or more arrays 95
  • 96. There are two ways to create indexed arrays: The index can be assigned automatically (index always starts at 0): $cars=array("Volvo","BMW","Toyota");  or the index can be assigned manually: $cars[0]="Volvo"; $cars[1]="BMW"; $cars[2]="Toyota"; 96
  • 97.  The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text containing the array values: Example  <?php $cars=array("Volvo","BMW","Toyota"); echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; ?> 97
  • 98. The count() function is used to return the length (the number of elements) of an array: Example <?php $cars=array("Volvo","BMW","Toyota"); echo count($cars); ?> 98
  • 99. To loop through and print all the values of an indexed array, you could use a for loop, like this: Example <?php $cars=array("Volvo","BMW","Toyota"); $arrlength=count($cars); for($x=0; $x<$arrlength; $x++) { echo $cars[$x]; echo "<br>"; } ?> 99
  • 100. Associative arrays are arrays that use named keys that you assign to them. There are two ways to create an associative array: $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); or: $age['Peter']="35"; $age['Ben']="37"; $age['Joe']="43"; The named keys can then be used in a script: Example <?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); echo "Peter is " . $age['Peter'] . " years old."; ?> 100
  • 101. 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  <?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); foreach($age as $x=>$x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; } ?> 101
  • 102.  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. 102
  • 103. $marks = array( "mohammad" => array ( "physics" => 35, "maths" => 30, "chemistry" => 39 ), " Zara" => array ( "physics" => 31, "maths" => 22, "chemistry" => 39 ) ); 103
  • 104. /* Accessing multi-dimensional array values */ echo "Marks for mohammad in physics : " ; echo $marks['mohammad']['physics'] . "<br />"; echo "Marks for zara in chemistry : " ; echo $marks['zara']['chemistry'] . "<br />"; 104
  • 105.  http://www.w3schools.com/php/  http://www.tutorialspoint.com/php/php_introduction.htm 105