You are on page 1of 19

9/17/2014

Outline
What is PHP?
History of PHP
Why PHP ?
What is PHP file?
What you need to start using PHP ?
Syntax PHP code .
echo & print Statement
Variables.
Data Types.
Constants &Operators.
Conditional Statements & Loops.

What is PHP? What is PHP? (contd)


Personal Homepage Tools/Form Interpreter Interpreted language, scripts are parsed at run-time rather
PHP is a Server-side Scripting Language designed specifically for than compiled beforehand
the Web. Executed on the server-side
An open source language Source-code not visible by client
PHP code can be embedded within an HTML page, which will View Source in browsers does not display the PHP code
be executed each time that page is visited. Various built-in functions allow for fast development

Compatible with many popular databases

History of PHP Why PHP ?


PHP (PHP: Hypertext Preprocessor) was created by Rasmus Lerdorf in 1994. It was initially developed for

HTTP usage logging and server-side form generation in Unix. PHP runs on different platforms (Windows, Linux, Unix, Mac OS X, etc.)
PHP 2 (1995) transformed the language into a Server-side embedded scripting language. Added database
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
support, file uploads, variables, arrays, recursive functions, conditionals, iteration, regular expressions, etc.
PHP has support for a wide range of databases
PHP 3 (1998) added support for ODBC data sources, multiple platform support, email protocols

(SNMP,IMAP), and new parser written by Zeev Suraski and Andi Gutmans . PHP is free. Download it from the official PHP resource: www.php.net
PHP 4 (2000) became an independent component of the web server for added efficiency. The parser was
PHP is easy to learn and runs efficiently on the server side
renamed the Zend Engine. Many security features were added.

PHP 5 (2004) adds Zend Engine II with object oriented programming, robust XML support using the libxml2

library, SOAP extension for interoperability with Web Services, SQLite has been bundled with PHP

1
9/17/2014

What does PHP code look like? What Can PHP Do?
Structurally similar to C/C++ PHP can generate dynamic page content

PHP can create, open, read, write, and close files on the server

Supports procedural and object-oriented PHP can collect form data

PHP can send and receive cookies


paradigm (to some degree)
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

What is a PHP File? What you need to start using PHP ?


Installation
PHP files can contain text, HTML, JavaScript code,
You will need
and PHP code
1. Web server ( Apache )
PHP code are executed on the server, and the 2. PHP ( version 5.3)

result is returned to the browser as plain HTML 3. Database ( MySQL 5 )

4. Text editor (Notepad)


PHP files have a default file extension of ".php
5. Web browser (Firefox )

6. www.php.net/manual/ en/install.php

Syntax PHP code Syntax PHP code


A PHP script can be placed anywhere in the Standard Style :
document. <?php ?>

A PHP script starts with Short Style:


<? ?>
<?php and ends with ?>
Script Style:
<SCRIPT LANGUAGE=php> </SCRIPT>
ASP Style:
<% echo Hello World!; %>

2
9/17/2014

Echo Echo - Example

The PHP command echo is used to output the parameters <?php


passed to it .
echo This my first statement in PHP language;
The typical usage for this is to send data to the clients web-
browser ?>
Syntax : void echo (string arg1 [, string argn...])

In practice, arguments are not passed in parentheses since


echo is a language construct rather than an actual function

Print Echo Vs Print


Improve this chart Echo Print

print is not actually a real function (it is a Parameters: echo can take more than one parameter when print only takes one parameter.
used without parentheses. The syntax is echo
expression [, expression[, expression] ... ]. Note
language construct) so you are not required to that echo ($arg1,$arg2) is invalid.

use parentheses with its argument list.


Return value: echo does not return any value print always returns 1 (integer)
<?php
Syntax: void echo ( string $arg1 [, string $... ] ) int print ( string $arg )
print("Hello World");
?> What is it?: In PHP, echo is not a function but a language In PHP, print is not a really function but a
construct. language construct. However, it behaves like a
function in that it returns a value.

Variables Variables
As with algebra, PHP variables can be used to hold values (x=5) or A variable name must begin with a letter or the underscore character

expressions (z=x+y). A variable name can only contain alpha-numeric characters and

Variable can have short names (like x and y) or more descriptive names underscores (A-z, 0-9, and _ )

(age, carname, totalvolume). A variable name should not contain spaces

Rules for PHP variables: Variable names are case sensitive ($y and $Y are two different variables)

A variable starts with the $ sign, followed by the name of the variable

3
9/17/2014

Variables Creating (Declaring) Variables


Case-sensitive ($Foo != $foo != $fOo)

Global and locally-scoped variables <?php


Global variables can be used anywhere
$name = ali
Local variables restricted to a function or class

Certain variable names reserved by PHP


echo( $name);
Form variables ($_POST, $_GET)
?>
Server variables ($_SERVER)

Creating (Declaring) Variables Variables


PHP has no command for declaring a variable.
<?php
A variable is created the moment you first assign a value to it:
$name = ali;
$txt="Hello world!"; $age = 23;
$x=5;
echo My name is $name and I am $age years old;

After the execution of the statements above, the variable txt will hold the

value Hello world!, and the variable xwill hold the value 5. ?>
Note: When you assign a text value to a variable, put quotes around the

value.

PHP is a Loosely Typed Language Variables


In the example above, notice that we did not have to tell PHP which data <?php
type the variable is.

PHP automatically converts the variable to the correct data type, $name = 'elijah';
depending on its value. $yearborn = 1975;
In a strongly typed programming language, we will have to declare (define)
$currentyear = 2005;
the type and name of the variable before using it.
$age = $currentyear - $yearborn;
echo ("$name is $age years old.");

?>

4
9/17/2014

Variables PHP Variable Scopes


The scope of a variable is the part of the script where the variable can be
<?php $name = Ali"; // declaration ?>
referenced/used.
<html>
PHP has four different variable scopes:
<head> <title>A simple PHP document</title> </head>

<body style = "font-size: 2em"> local


<p> <strong> global
<!-- print variable names value -->
static
Welcome to PHP, <?php echo( "$name" ); ?>!

</strong> </p>
Parameter

</body> - In chapter function we will talk about theme.


</html>

String Variables in PHP PHP strings can be specified in four ways

string variables are used for values that contain characters. Single quoted strings will display things almost completely "as is." Variables and most escape
sequences will not be interpreted. The exception is that to display a literal single quote, you
After we have created a string variable we can manipulate it. A string can be used
can escape it with a back slash \', and to display a back slash, you can escape it with another
directly in a function or it can be stored in a variable. backslash \\ (So yes, even single quoted strings are parsed).

In the example below, we create a string variable called txt, then we assign the text

"Hello world!" to it. Then we write the value of the txt variable to the output:
<?php <?php
$txt = my string ; $txt = my string ;

echo $txt; // my string echo $txt; // $txt


<?php
$txt="Hello world!"; ?> ?>
echo $txt;
?>

PHP strings can be specified in four ways PHP strings can be specified in four ways
Double quote strings will display a host of escaped characters (including some regexes), and Heredoc string syntax works like double quoted strings. It starts with <<<. After this operator,
variables in the strings will be evaluated. An important point here is that you can use curly an identifier is provided, then a newline. The string itself follows, and then the same
braces to isolate the name of the variable you want evaluated. For example let's say you have identifier again to close the quotation. You don't need to escape quotes in this syntax.
the variable $type and you what to echo "The $types are" That will look for the Nowdoc (since PHP 5.3.0) string syntax works essentially like single quoted strings. The
variable $types. To get around this use echo "The {$type}s are" You can put the left brace difference is that not even single quotes or backslashes have to be escaped. A nowdoc is
before or after the dollar sign. Take a look at string parsing to see how to use array variables identified with the same <<< sequence used for heredocs, but the identifier which follows is
and such. enclosed in single quotes, e.g. <<<'EOT'. No parsing is done in nowdoc.

<?php <?php
$txt = my string; $txt = my string ;

echo $txt; // my string echo $txt; // my string

?> ?>

5
9/17/2014

PHP strings can be specified in four ways PHP strings can be specified in four ways

Heredoc <?php Nowdoc <?php


$name='MyName'; $name='MyName';
echo <<<EOT echo <<<'EOT'
My name is "$name". My name is "$name".
I am printing some A Now, I am printing some A Now,
I am printing some {A}. I am printing some {A}.
This should print a capital 'A': \x41 This should print a capital 'A': \x41
EOT; EOT;
?> ?>

My name is "$name".
My name is "MyName". I am printing some A Now, I am printing some A Now,
I am printing some {A}. I am printing some {A}. This should print a capital 'A': \x41
This should print a capital 'A': A

Single & Double Quotes Single & Double Quotes

<?php <?php
echo Hello world <br>;
$word = World;
echo Hello world;
echo Hello $word <br>;
?>
echo Hello $word <br>;

?>

Comments in PHP Whitespace

// or # for single line You cant have any whitespace between <? and
/* */ for multiline php.
/*
You cant break apart keywords (e.g :whi le,func
this is my comment one
tion,fo r)
this is my comment two
this is my comment three
You cant break apart varible names and function
*/ names (e.g:$var name,function f 2)

6
9/17/2014

The PHP Concatenation Operator The PHP Concatenation Operator


here is only one string operator in PHP.
<?php
The concatenation operator (.) is used to join two string values together. $string1=Hello;
The example below shows how to concatenate two string variables together: $string2=PHP;
$string3=$string1 . . $string2;
Print $string3;
?>
<?php
$txt1="Hello!";
$txt2=" world !"; Hello PHP
echo $txt1 . " " . $txt2; // Hello world !
?>

Escaping the Character Example


<?php
If the string has a set of double quotation marks that must
$foo = 25; // Numerical variable
remain visible, use the \ [backslash] before the quotation $bar = Hello; // String variable
echo $bar; // Outputs Hello
marks to ignore and display them.
echo $foo,$bar; // Outputs 25Hello
echo 5x5=,$foo; // Outputs 5x5=25
<?php
echo 5x5=$foo; // Outputs 5x5=25
$heading="\"Computer Science\""."<br>";
echo 5x5=$foo; // Outputs 5x5=$foo
$heading1=@"Computer Science";
?>
echo $heading;
"Computer Science"
echo $heading1; Computer Science Notice how echo 5x5=$foo outputs $foo rather than replacing it with 25

?> Strings in single quotes ( ) are not interpreted or evaluated by PHP

This is true for both variables and character escape-sequences (such as \n or \\)

Data type Get type


gettype Get the type of a variable
Returns the type of the PHP variable var.

Data type Description


int, Whole numbers (i.e., numbers without a decimal point).
integer
float, Real numbers (i.e., numbers containing a decimal point).
<?php
double
string Text enclosed in either single ('') or double ("") quotes.
$a = 1; integer
bool,
Boolean
True or false. $b = 1.2; double
array Group of elements of the same type. $c = "abc"; string
object Group of associated data and methods.
Resource An external data source.
echo gettype($a)."<br>";
NULL No value. echo gettype($b)."<br>";
echo gettype($c)."<br>";
?>

7
9/17/2014

Set type Set type


<?php

$testString = 10.2abc;
<?php // call function settype to convert variable

$foo = "5bar"; // string // testString to different data types

print( "$testString" ); 10.2abc as a double is 10.2


$bar = true; // boolean 10.2 as an integer is 10
settype( $testString, "double" ); Converting back to a string results in 10

print( " as a double is $testString <br />" );

settype($foo, "integer"); // $foo is now 5 (integer) print( "$testString" );

settype( $testString, "integer" );


settype($bar, "string"); // $bar is now "1" (string)
print( " as an integer is $testString <br />" );
?>
settype( $testString, "string" );

print( "Converting back to a string results in

$testString <br /><br />" );

?>

Casting Data type Casting Data type


Now using type casting instead:
<?php As a string - 98.6 degrees $variable = (datatype) $variable or value
As a double - 98.6
$data = "98.6 degrees"; As an integer - 98 <?php
echo "Now using type casting instead: <br>"; $data = "98.6 degrees";
echo "As a string - ".(string) $data ; echo "Now using type casting instead: <br>";
echo "<br> As a double - ".(double) $data; echo "As a string - ".(string) $data ;
echo "<br> As an integer - ".(integer) $data; echo "<br> As a double - ".(double) $data;
?> echo "<br> As an integer - ".(integer) $data;

?>

Casting Data type PHP Operators

<?php The assignment operator = is used to assign values


to variables in PHP.
$a = 12.4 abc The arithmetic operator + is used to add values
echo (int) $a; together in PHP.
echo (double) ($a); Assignment operators
Syntactical shortcuts
echo (float) ($a);
Before being assigned values, variables have value undef
echo (string) ($a); Constants
Named values
?> define function

8
9/17/2014

PHP Operators Arithmetic Operators


Operator Name Description Example Result
Arithmetic Operators
x+y Addition Sum of x and y 2+2 4
Assignment Operators x-y Subtraction Difference of x and y 5-2 3

Incrementing/Decrementing Operators x*y Multiplication Product of x and y 5*2 10

Comparison Operators x/y Division Quotient of x and y 15 / 5 3

Logical Operators x%y Modulus Remainder of x divided by y 5%2 1


10 % 8 2
10 % 2 0

-x Negation Opposite of x -2

a.b Concatenation Concatenate two strings "Hi" . "Ha" HiHa

Assignment Operators Arithmetic Operations


Assignment Same as... Description <?php
$a=15;
$b=30;
x=y x=y The left operand gets set to the value of the expression on the $total=$a+$b;
right
echo $total;
x += y x=x+y Addition echo<p><h1>$total</h1>;
// total is 45
x -= y x=x-y Subtraction ?>

x *= y x=x*y Multiplication
$a - $b // subtraction
x /= y x=x/y Division
$a * $b // multiplication
x %= y x=x%y Modulus
$a / $b // division
a .= b a=a.b Concatenate two strings $a += 5 // $a = $a+5 Also works for *= and /=

Incrementing/Decrementing Operators Arithmetic Operations


<?php
Operator Name Description
$a =1;
echo $a++;
++ x Pre-increment Increments x by one, then returns x // output 1,$a is now equal to 2

echo ++$a;
x ++ Post-increment Returns x, then increments x by one
// output 3,$a is now equal to 3

-- x Pre-decrement Decrements x by one, then returns x echo --$a;


// output 2,$a is now equal to 2

x -- Post-decrement Returns x, then decrements x by one echo $a--;


// output 2,$a is now equal to 1

?>

9
9/17/2014

Arithmetic Operations Arithmetic Operations


<?php
<?php
// Multiplication
$num1 = 10;
echo $num1* $num2 . <br>;
$num2 =20;
// Division
// addition
Echo $num1/num2 . <br> ;
echo $num1+$mum2 . <br>;
//increment
//subtraction
$num1++;
echo $num1 - $num2 . <br>;
$Num2--;
// multiplication
Echo $num1;
?>
?>

Arithmetic Operations Dumps information about a variable

void var_dump ($expression [,... ] )

This function displays structured information about one or more expressions that
<?php includes its type and value. Arrays and objects are explored recursively with values
indented to show structure.

$a =(int)(test); // $a==0 <?php


echo ++$a; $b = 3.1;
$c = true;
var_dump($b);
var_dump($c); float 3.1
?> //or var_dump($b,$c); boolean true

?>

Comparison Operators Comparison Operators

Operator Name Description Example


<?php
x == y Equal True if x is equal to y 5==8 returns false

x === y Identical True if x is equal to y, and they are of same 5==="5" returns false var_dump(0 == "a"); // 0 == 0 -> true boolean true
type boolean false
var_dump("1" != "01"); // 1 != 1 -> false boolean true
x != y Not equal True if x is not equal to y 5!=8 returns true
boolean false
x <> y Not equal True if x is not equal to y 5<>8 returns true var_dump("10" == "1e1"); // 10 == 10 -> true boolean false
boolean true
x !== y Not identical True if x is not equal to y, or they are not of 5!=="5" returns true
same type var_dump("10" == "1ee1"); // 10 == 1 -> false
x>y Greater than True if x is greater than y 5>8 returns false
var_dump(100 === "100"); // 100 == 100 -> false
x<y Less than True if x is less than y 5<8 returns true
var_dump("100" === "100"); // 100 == 100 -> true
x >= y Greater than or equal to True if x is greater than or equal to y 5>=8 returns false

?>
x <= y Less than or equal to True if x is less than or equal to y 5<=8 returns true

10
9/17/2014

Logical Operators Logical Operators

Operator Name Description Example <?php


x and y And True if both x and y are true x=6 $a = (false && true);
y=3
(x < 10 and y > 1) returns true
$b = (true || false);
x or y Or True if either or both x and y are true x=6
y=3 $c = (false and flase); boolean true
(x==6 or y==5) returns true boolean false
x xor y Xor True if either x or y is true, but not both x=6 $d = (true or true); boolean false
y=3
(x==6 xor y==3) returns false $e = false || true; boolean true

x && y And True if both x and y are true x=6 $f = false or true;
y=3
(x < 10 && y > 1) returns true
var_dump($e, $f);
x || y Or True if either or both x and y are true x=6
y=3 $g = true && false;
(x==5 || y==5) returns false
!x Not True if x is not true x=6 $h = true and false;
y=3
!(x==y) returns true var_dump($g, $h);
?>

Define function - constant VALUE Define function - constant VALUE


<?php
define( variable name as string , value );
$a = 5;
print( "The value of variable a is $a <br />" );
Variable name as string : the name of variable in single or double quotation
// define constant VALUE
.
define( "VALUE", 5 );

// add constant VALUE to variable $a


<?php
$a = $a + VALUE;
define(variable ,10);
print( "Variable a after adding constant VALUE
echo variable ; //10 is $a <br />" );
?>

Define function - constant VALUE Define function - constant VALUE


// multiply variable $a by 2 // print an uninitialized variable
$a *= 2;
print( "Using a variable before initializing:
print( "Multiplying variable a by 2 yields $a <br />" );
// test if variable $a is less than 50 $nothing <br />" );
if ( $a < 50 )
// add constant VALUE to an uninitialized variable
print( "Variable a is less than 50 <br />" );
// add 40 to variable $a $test = $num + VALUE;
$a += 40;
print( "An uninitialized variable plus constant
print( "Variable a after adding 40 is $a <br />" );
// test if variable $a is 50 or less VALUE yields $test <br />" );
if ( $a < 51 )
print( "Variable a is still 50 or less<br />" );
// test if variable $a is between 50 and 100, inclusive // add a string to an integer
elseif ( $a < 101 ) $str = "3 dollars";
print( "Variable a is now between 50 and 100, inclusive<br />" );
else $a += $str;
print( "Variable a is now greater than 100<br />" ); print( "Adding a string to variable a yields $a
<br />" );
?>

11
9/17/2014

Referencing Operators Referencing Operators


We know the assignment operators work by value ,by copy the value to other But we can change the value of variable $a by the reference , that mena connect
expression ,if the value in right hand change the value in left is not change . right hand to left hand ,
Ex: Example:

<?php
<?php $a =10;
$a =10; $b = &$a;
$b =$a; $b= 20;
$b =20 echo $a; // 20
Echo $a; // 10 ?>
?>

PHP Conditional Statements The if Statement


The if statement is used to execute some code only if a specified condition is true.
Very often when you write code, you want to perform different
actions for different decisions. You can use conditional statements in
if (condition)
your code to do this. {
code to be executed if condition is true;
In PHP we have the following conditional statements: }
if statement - executes some code only if a specified condition is true
if...else statement - executes some code if a condition is true and another code if
<?php
the condition is false
$t=5;
if...else if....else statement - selects one of several blocks of code to be executed if ($t<10)
switch statement - selects one of many blocks of code to be executed {
echo "hello john";
} hello john
?>

The if...else Statement The if...else Statement


Use the if....else statement to execute some code if a condition is true and another
code if the condition is false.
<?php
if (condition) $t=55;
{ if ($t<20)
code to be executed if condition is true; {
} echo "Have a good day!";
else }
{ else
code to be executed if condition is false; {
} echo "Have a good night!";
}
?>

Have a good night!

12
9/17/2014

The if...else if....else Statement The if...else if....else Statement


Use the if....else if...else statement to select one of several blocks of code to be <?php
$t=7;
executed.
if (condition) if ($t<10)
{ {
code to be executed if condition is true; echo "Have a good morning!";
} }
else if (condition) else if ($t<20)
{ {
code to be executed if condition is true; echo "Have a good day!";
} }
else else
{ {
code to be executed if condition is false; echo "Have a good night!";
} } Have a good morning!
?>

The switch Statement The switch Statement


Use the switch statement to select one of many blocks of code to be executed. <?php
$favcolor="red";
switch ($favcolor)
{
switch (n) case "red":
{ echo "Your favorite color is red!";
case label1: break;
code to be executed if n=label1; case "blue":
break; echo "Your favorite color is blue!";
case label2: break;
Your favorite color is red!
case "green":
code to be executed if n=label2;
echo "Your favorite color is green!";
break; break;
default: default:
code to be executed if n is different from both echo "Your favorite color is neither red, blue, or green!";
label1 and label2; }
} ?>

PHP Loops The while Loop


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

condition is true. while (condition)


{
In PHP, we have the following looping statements: code to be executed; The number is 1
} The number is 2
while - loops through a block of code while a specified condition is true
The number is 3
do...while - loops through a block of code once, and then repeats the loop as <?php The number is 4
$i=1; The number is 5
long as a specified condition is true while($i<=5)
for - loops through a block of code a specified number of times {
echo "The number is " . $i . "<br>";
foreach - loops through a block of code for each element in an array $i++;
}
?>

13
9/17/2014

The do...while Statement The do...while Statement


The do...while statement will always execute the block of code once, it will then
<?php
check the condition, and repeat the loop while the condition is true. $i=1;
do
{
do
{
$i++;
code to be executed; echo "The number is " . $i . "<br>";
}
<?php }
while (condition);
$i=1; while ($i<=5);
do The number is 2
{ The number is 3 ?> The number is 2
$i++; The number is 4 The number is 3
echo "The number is " . $i . "<br>";
The number is 5 The number is 4
}
The number is 6 The number is 5
while ($i<=5); The number is 6
?>

The for Loop The for Loop


The for loop is used when you know in advance how many times the script should condition: Evaluated for each loop iteration. If it evaluates to TRUE,
run.
for (init; condition; increment) the loop continues. If it evaluates to FALSE, the loop ends.
{
code to be executed; increment: Mostly used to increment a counter (but can be any code
}
to be executed at the end of the iteration)

Note: The init and increment parameters above can be empty or


Parameters:
have multiple expressions (separated by commas).
init: Mostly used to set a counter (but can be any code to be executed once at
the beginning of the loop)

The for Loop The foreach Loop


<?php The foreach loop is used to loop through arrays.
for ($i=1; $i<=5; $i++)
{
We well talk about this in chapter array
echo "The number is " . $i . "<br>";
}
?> The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

14
9/17/2014

Isset Function Isset Function


bool isset ( $var ) <?php
Determine if a variable is set and is not NULL. $var = '';
If a variable has been unset with unset(), it will no longer be set. isset() will
// This will evaluate to TRUE so the text will be printed.
return FALSE if testing a variable that has been set to NULL. Also note that
if (isset($var))
a NULLbyte ("\0") is not equivalent to the PHP NULL constant.

If multiple parameters are supplied then isset() will return TRUE only if all of the
{

parameters are set. Evaluation goes from left to right and stops as soon as an echo "This var is set so I will print.";
unset variable is encountered. }

?>

Unset Function unset Function


void unset ( $var)
<?php
unset() destroys the specified variables.

The behavior of unset() inside of a function can vary depending on what type of $foo = 'bar';
variable you are attempting to destroy.
echo $foo;
If a globalized variable is unset() inside of a function, only the local variable is
destroyed. The variable in the calling environment will retain the same value as
unset($foo);
before unset() was called.
echo $foo;

?>

Info PHP Page Goto


<?php
goto a;
<?php echo 'Foo';

a:
phpinfo(); echo 'Bar';
?>
<?php
?> for($i=0,$j=50; $i<100; $i++) {
while($j--) {
if($j==17) goto end;
}
}
echo "i = $i";
end:
echo 'j hit 17';
?>

15
9/17/2014

if/else if/else statement

<?php
if ($foo == 0) {
echo The variable foo is equal to 0;

Chapter Example }
else if (($foo > 0) && ($foo <= 5)) {
echo The variable foo is between 1 and 5;
}
else {
echo The variable foo is equal to .$foo;
}

?>

Switch Statment Switch - Example


<?php
<?php
$count=0; $total = 0;
switch($count) $i = 2;
{
case 0: switch($i) {
echo hello PHP3. ; case 6: $total = 99; break;
break; case 1: $total += 1;break;
2
case 1:
case 2:$total += 2;break;
echo hello PHP4. ;
break; case 3: $total += 3; ;break;
default: hello PHP3 case 4:$total += 4; break;
echo hello PHP5. ;
break; default : $total += 5;break;
} }

?> echo $total;


?>

For Loop For - Example


<?php
$count=0; <?php
for($count = 0;$count <3,$count++)
{
Print hello PHP. ; for ($i = 1; $i <= 10; $i++) {
}
?>
echo $i;
}

hello PHP. hello PHP. hello PHP.

?>

16
9/17/2014

For-Example While Loop


<?php
<?php
$brush_price = 5; $count=0;
echo "<table border=\"1\" align=\"center\">"; while($count<3)
echo "<tr><th>Quantity</th>"; {
echo "<th>Price</th></tr>"; echo hello PHP. ;
$count += 1;
for ( $counter = 10; $counter <= 100; $counter += 10)
// $count = $count + 1;
{ // or
echo "<tr><td>"; // $count++;
echo $counter; }
echo "</td><td>"; ?>
echo $brush_price * $counter;
echo "</td></tr>"; hello PHP. hello PHP. hello PHP.
}
echo "</table>";
?>

While - Example Do ... While Loop


<?php
<?php $count=0;
do
$i = 0; {
while ($i++ < 5) echo hello PHP. ;
$count += 1;
{ // $count = $count + 1;
// or
echo loop number : .$i; // $count++;
} }
while($count<3);
?> ?>

hello PHP. hello PHP. hello PHP.

Do..While For..If
<?php
<?php $rows = 4;
$i = 0; echo '<table><tr>';
do { for($i = 0; $i < 10; $i++){

echo $i; echo '<td>' . $i . '</td>';

} while ($i > 0); if(($i + 1) % $rows == 0){

?> echo '</tr><tr>';


}
}
echo '</tr></table>';
?>

17
9/17/2014

For Nested For

<?php
//this is a different way to use the 'for' <?php
//Essa uma maneira diferente de usar o 'for' for($a=0;$a<10;$a++){
for($i = $x = $z = 1; $i <= 10;$i++,$x+=2,$z=&$p){
for($b=0;$b<10;$b++){
$p = $i + $x; for($c=0;$c<10;$c++){
for($d=0;$d<10;$d++){
echo "\$i = $i , \$x = $x , \$z = $z <br />";
echo $a.$b.$c.$d.", ";
} }
}
?>
}
}
?>

While - Switch Continue


<?php
$i = 0; <?php
while (++$i) {
switch ($i) { for ($i = 0; $i < 5; ++$i) {
case 5: if ($i == 2)
echo "At 5<br />\n";
break 1; /* Exit only the switch. */
continue
case 10: print "$i\n";
echo "At 10; quitting<br />\n"; }
break 2; /* Exit the switch and the while. */
default: ?>
break;
}
}
?>

If - Switch Do..While - IF
<?php
$i = 1;
if ($i == 0) { <?php
echo "i equals 0"; do {
} elseif ($i == 1) {
echo "i equals 1";
if ($i < 5) {
} elseif ($i == 2) { echo "i is not big enough";
echo "i equals 2"; break;
} }
switch ($i) { $i *= $factor;
case 0: if ($i < $minimum_limit) {
echo "i equals 0"; break;
break;
case 1:
}
echo "i equals 1"; echo "i is ok";
break;
case 2: /* process i */
echo "i equals 2";
break;
} } while (0);
?> ?>

18
9/17/2014

If in other style

<?php
$hour = 11;

echo $foo = ($hour < 12) ? "Good morning!" : "Good


afternoon!";

?>

19

You might also like