+ All Categories
Home > Documents > Outline What is PHP? History of PHP Why PHP ? What is PHP file? What you need to start using PHP ?...

Outline What is PHP? History of PHP Why PHP ? What is PHP file? What you need to start using PHP ?...

Date post: 17-Dec-2015
Category:
Upload: ashlynn-grant
View: 244 times
Download: 1 times
Share this document with a friend
109
Chapter - 1 The Basic PHP PHP: Hypertext Preprocesso
Transcript

Chapter - 1

The Basic PHP

PHP: Hypertext Preprocessor

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?

Personal Homepage Tools/Form Interpreter

PHP is a Server-side Scripting Language designed

specifically for the Web.

An open source language

PHP code can be embedded within an HTML page,

which will be executed each time that page is

visited.

What is PHP? (cont’d)

• Interpreted language, scripts are parsed at run-time

rather than compiled beforehand

• Executed on the server-side

• Source-code not visible by client

• ‘View Source’ in browsers does not display the PHP code

• Various built-in functions allow for fast development

• Compatible with many popular databases

History of 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 2 (1995) transformed the language into a Server-side embedded scripting

language. Added database support, file uploads, variables, arrays, recursive

functions, conditionals, iteration, regular expressions, etc.

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 4 (2000) became an independent component of the web server for added

efficiency. The parser was 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

Why PHP ?

PHP runs on different platforms (Windows, Linux, Unix, Mac

OS X, etc.)

PHP is compatible with almost all servers used today

(Apache, IIS, etc.)

PHP has support for a wide range of databases

PHP is free. Download it from the official PHP resource:

www.php.net

PHP is easy to learn and runs efficiently on the server side

What does PHP code look like?

• Structurally similar to C/C++

• Supports procedural and object-oriented

paradigm (to some degree)

What Can PHP Do? PHP can generate dynamic page content

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

PHP can collect form data

PHP can send and receive cookies

PHP can add, delete, modify data in your database

PHP can restrict users to access some pages on your website

PHP can encrypt data

With PHP you are not limited to output HTML. You can output

images, PDF files, and even Flash movies. You can also output

any text, such as XHTML and XML

What is a PHP File?

PHP files can contain text, HTML, JavaScript

code, and PHP code

PHP code are executed on the server, and the

result is returned to the browser as plain

HTML

PHP files have a default file extension of

".php”

What you need to start using PHP ?

Installation

You will need

1. Web server ( Apache )

2. PHP ( version 5.3)

3. Database ( MySQL 5 )

4. Text editor (Notepad)

5. Web browser (Firefox )

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

Syntax PHP code

A PHP script can be placed anywhere in the document.

A PHP script starts with

<?php and ends with ?>

Syntax PHP code

• Standard Style :

<?php …… ?>

• Short Style:

<? … ?>

• Script Style:

<SCRIPT LANGUAGE=‘php’> </SCRIPT>

• ASP Style:

<% echo “Hello World!”; %>

Echo

The PHP command ‘echo’ is used to output the

parameters passed to it .

The typical usage for this is to send data to the client’s

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

Echo - Example

<?php

echo “ This my first statement in PHP

language“;

?>

Print

print is not actually a real function (it is a

language construct) so you are not

required to use parentheses with its

argument list.<?php

print("Hello World");?>

Echo Vs Print

Improve this chart Echo Print

Parameters: echo can take more than one

parameter when used without

parentheses. The syntax is echo

expression [, expression[, expression]

... ]. Note that echo ($arg1,$arg2) is

invalid.

print only takes one parameter.

Return value: echo does not return any value print always returns 1 (integer)

Syntax: void echo ( string $arg1 [, string

$... ] )

int print ( string $arg )

What is it?: In PHP, echo is not a function but a

language construct.

In PHP, print is not a really function

but a language construct. However, it

behaves like a function in that it

returns a value.

Variables As with algebra, PHP variables can be used to hold values

(x=5) or expressions (z=x+y).

Variable can have short names (like x and y) or more

descriptive names (age, carname, totalvolume).

Rules for PHP variables:

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

the variable

Variables A variable name must begin with a letter or the underscore

character

A variable name can only contain alpha-numeric characters

and underscores (A-z, 0-9, and _ )

A variable name should not contain spaces

Variable names are case sensitive ($y and $Y are two

different variables)

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

Global and locally-scoped variables

Global variables can be used anywhere

Local variables restricted to a function or class

Certain variable names reserved by PHP

Form variables ($_POST, $_GET)

Server variables ($_SERVER)

Creating (Declaring) Variables

<?php

$name = “ali”

echo( $name);

?>

Creating (Declaring) Variables

PHP has no command for declaring a variable.

A variable is created the moment you first assign a value to

it:

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.

$txt="Hello world!";$x=5;

Variables

<?php

$name = “ali”;

$age = 23;

echo “ My name is $name and I am $age years

old”;

?>

PHP is a Loosely Typed Language

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 a strongly typed programming language, we will have to

declare (define) the type and name of the variable before

using it.

Variables<?php

$name = 'elijah'; $yearborn = 1975; $currentyear = 2005;$age = $currentyear - $yearborn; echo ("$name is $age years old.");

?>

Variables

<?php $name = “Ali"; // declaration ?>

<html>

<head> <title>A simple PHP document</title> </head>

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

<p> <strong>

<!-- print variable name’s value -->

Welcome to PHP, <?php echo( "$name" ); ?>!

</strong> </p>

</body>

</html>

PHP Variable Scopes

The scope of a variable is the part of the script where the

variable can be referenced/used.

PHP has four different variable scopes:

local

global

static

Parameter

- In chapter function we will talk about theme.

String Variables in PHP

string variables are used for values that contain characters.

After we have created a string variable we can manipulate it. A

string can be used directly in a function or it can be stored in a

variable.

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

$txt="Hello world!";echo $txt;

?>

PHP strings can be specified in four ways 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 can escape it with a back slash \', and to

display a back slash, you can escape it with another backslash \\ (So yes,

even single quoted strings are parsed).

<?php$txt = ‘my string ‘;

echo $txt; // my string

?>

<?php$txt = ‘my string

‘;

echo ‘$txt’; // $txt

?>

PHP strings can be specified in four ways Double quote strings will display a host of escaped characters (including

some regexes), and variables in the strings will be evaluated. An important

point here is that you can use curly braces to isolate the name of the

variable you want evaluated. For example let's say you have the

variable $type and you what to echo "The $types are" That will look for the

variable $types. To get around this use echo "The {$type}s are" You can

put the left brace before or after the dollar sign. Take a look at 

string parsing to see how to use array variables and such.

<?php$txt = “my string”;

echo $txt; // my string

?>

<?php$txt = “my string “;

echo “$txt”; // my string

?>

PHP strings can be specified in four ways Heredoc string syntax works like double quoted strings. It starts with <<<.

After this operator, an identifier is provided, then a newline. The string itself

follows, and then the same identifier again to close the quotation. You don't

need to escape quotes in this syntax.

Nowdoc (since PHP 5.3.0) string syntax works essentially like single quoted

strings. The difference is that not even single quotes or backslashes have

to be escaped. A nowdoc is identified with the same <<< sequence used

for heredocs, but the identifier which follows is enclosed in single quotes,

e.g. <<<'EOT'. No parsing is done in nowdoc.

PHP strings can be specified in four ways Heredoc  <?php

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

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

PHP strings can be specified in four ways Nowdoc  <?php

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

?>

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

Single & Double Quotes

<?php

echo “ Hello world <br>”;

echo ‘ Hello world’;

?>

Single & Double Quotes

<?php

$word = ‘ World’;

echo “ Hello $word <br>”;

echo ‘ Hello $word <br>’;

?>

Comments in PHP

• // or # for single line

• /* */ for multiline

• /*

this is my comment one

this is my comment two

this is my comment three

*/

Whitespace

• You cant have any whitespace between <?

and php.

• You cant break apart keywords (e.g :whi

le,func tion,fo r)

• You cant break apart varible names and

function names (e.g:$var name,function f 2)

The PHP Concatenation Operator

here is only one string operator in PHP.

The concatenation operator (.) is used to join two string values

together.

The example below shows how to concatenate two string variables

together:

<?php$txt1="Hello!";$txt2=" world !";echo $txt1 . " " . $txt2; // Hello world !

?>

The PHP Concatenation Operator

<?php

$string1=“Hello”;

$string2=“PHP”;

$string3=$string1 . “ ” . $string2;

Print $string3;

?>

Hello PHP

Escaping the Character

• If the string has a set of double quotation marks

that must remain visible, use the \ [backslash]

before the quotation marks to ignore and display

them.<?php

$heading="\"Computer Science\""."<br>";

$heading1=@"Computer Science";

echo $heading;

echo $heading1;

?>

"Computer Science"Computer Science 

Example

• 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 “\\”)

<?php

$foo = 25; // Numerical variable

$bar = “Hello”; // String variable

echo $bar; // Outputs Hello

echo $foo,$bar; // Outputs 25Hello

echo “5x5=”,$foo; // Outputs 5x5=25

echo “5x5=$foo”;// Outputs 5x5=25

echo ‘5x5=$foo’; // Outputs 5x5=$foo

?>

Data type

Data type Description int,

integer Whole numbers (i.e., numbers without a decimal point).

float, double

Real numbers (i.e., numbers containing a decimal point).

string Text enclosed in either single ('') or double ("") quotes. bool,

Boolean True or false.

array Group of elements of the same type. object Group of associated data and methods.

Resource An external data source. NULL No value.

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

<?php$a = 1;$b = 1.2;$c = "abc";echo gettype($a)."<br>";echo gettype($b)."<br>";echo gettype($c)."<br>";?>

integerdoublestring

Set type

<?php

$foo = "5bar"; // string

$bar = true;   // boolean

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

settype($bar, "string");  // $bar is now "1" (string)

?>

Set type<?php

$testString = “10.2abc”;

// call function settype to convert variable

// testString to different data types

print( "$testString" );

settype( $testString, "double" );

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

print( "$testString" );

settype( $testString, "integer" );

print( " as an integer is $testString <br />" );

settype( $testString, "string" );

print( "Converting back to a string results in

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

?>

10.2abc as a double is 10.2 10.2 as an integer is 10 Converting back to a string results in 10 

Casting Data type

<?php

$data = "98.6 degrees";

echo "Now using type casting instead: <br>";

echo "As a string - ".(string) $data ;

echo "<br> As a double - ".(double) $data;

echo "<br> As an integer - ".(integer) $data;

?>

Now using type casting instead: As a string - 98.6 degreesAs a double - 98.6As an integer - 98

Casting Data type

<?php

$data = "98.6 degrees";

echo "Now using type casting instead: <br>";

echo "As a string - ".(string) $data ;

echo "<br> As a double - ".(double) $data;

echo "<br> As an integer - ".(integer) $data;

?>

$variable = (datatype) $variable or value

Casting Data type

<?php

$a = “ 12.4 abc”

echo (int) $a;

echo (double) ($a);

echo (float) ($a);

echo (string) ($a);

?>

PHP Operators

• The assignment operator = is used to assign values to variables in PHP.

• The arithmetic operator + is used to add values together in PHP.

• Assignment operators Syntactical shortcuts Before being assigned values, variables have

value undef• Constants

Named values define function

PHP Operators

• Arithmetic Operators• Assignment Operators• Incrementing/Decrementing

Operators• Comparison Operators• Logical Operators

Arithmetic OperatorsOperator Name Description Example Result

x + y Addition Sum of x and y 2 + 2 4

x - y Subtraction Difference of x and y 5 - 2 3

x * y Multiplication Product of x and y 5 * 2 10

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

x % y Modulus Remainder of x divided by y 5 % 210 % 810 % 2

120

- x Negation Opposite of x - 2  

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

Assignment Operators

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

a .= b a = a . b Concatenate two strings

Arithmetic Operations

• $a - $b // subtraction• $a * $b // multiplication• $a / $b // division• $a += 5 // $a = $a+5 Also works for *= and /=

<?php$a=15;$b=30;$total=$a+$b;echo $total;

echo“<p><h1>$total</h1>”;// total is 45

?>

Incrementing/Decrementing Operators

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

Arithmetic Operations<?php

$a =1; echo $a++; // output 1,$a is now equal to 2 echo ++$a; // output 3,$a is now equal to 3

echo --$a; // output 2,$a is now equal to 2 echo $a--; // output 2,$a is now equal to 1

?>

Arithmetic Operations

<?php

$num1 = 10;

$num2 =20;

// addition

echo $num1+$mum2 . ‘<br>’;

//subtraction

echo $num1 - $num2 . ‘<br>’;

// multiplication

?>

Arithmetic Operations<?php

// Multiplication

echo $num1* $num2 . ‘<br>’;

// Division

Echo $num1/num2 . ‘<br>’ ;

//increment

$num1++;

$Num2--;

Echo $num1;

?>

Arithmetic Operations

<?php

$a =(int)(‘test’); // $a==0 echo ++$a;

?>

Dumps information about a variable

This function displays structured information about one or more

expressions that includes its type and value. Arrays and objects are

explored recursively with values indented to show structure.

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

<?php

$b = 3.1;$c = true;var_dump($b);var_dump($c);//or var_dump($b,$c);

?>

float 3.1 boolean true

Comparison Operators

Operator Name Description Example

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 type

5==="5" returns false

x != y Not equal True if x is not equal to y 5!=8 returns true

x <> y Not equal True if x is not equal to y 5<>8 returns true

x !== y Not identical True if x is not equal to y, or they are not of same type

5!=="5" returns true

x > y Greater than True if x is greater than y 5>8 returns false

x < y Less than True if x is less than y 5<8 returns 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

Comparison Operators

<?php

var_dump(0 == "a"); // 0 == 0 -> true

var_dump("1" != "01"); // 1 != 1 -> false

var_dump("10" == "1e1"); // 10 == 10 -> true

var_dump("10" == "1ee1"); // 10 == 1 -> false

var_dump(100 === "100"); // 100 == 100 -> false

var_dump("100" === "100"); // 100 == 100 -> true

?>

boolean true boolean false boolean true boolean false boolean false boolean true

Logical Operators

Operator Name Description Example

x and y And True if both x and y are true x=6y=3 

(x < 10 and y > 1) returns true

x or y Or True if either or both x and y are true x=6y=3 

(x==6 or y==5) returns true

x xor y Xor True if either x or y is true, but not both

x=6y=3 

(x==6 xor y==3) returns false

x && y And True if both x and y are true x=6y=3

(x < 10 && y > 1) returns true

x || y Or True if either or both x and y are true x=6y=3

(x==5 || y==5) returns false

! x Not True if x is not true x=6y=3

!(x==y) returns true

Logical Operators

<?php

$a = (false && true);

$b = (true || false);

$c = (false and flase);

$d = (true or true);

$e = false || true;

$f = false or true;

var_dump($e, $f);

$g = true && false;

$h = true and false;

var_dump($g, $h);

?>

boolean true boolean false boolean false boolean true

Define function - constant VALUE

Variable name as string : the name of variable in single or

double quotation .

<?phpdefine(‘variable ’,10);echo variable ; //10

?>

define( variable name as string , value );

Define function - constant VALUE

<?php

$a = 5;

print( "The value of variable a is $a <br />" );

// define constant VALUE

define( "VALUE", 5 );

// add constant VALUE to variable $a

$a = $a + VALUE;

print( "Variable a after adding constant VALUE

is $a <br />" );

Define function - constant VALUE

// multiply variable $a by 2

$a *= 2;

print( "Multiplying variable a by 2 yields $a <br />" );

// test if variable $a is less than 50

if ( $a < 50 )

print( "Variable a is less than 50 <br />" );

// add 40 to variable $a

$a += 40;

print( "Variable a after adding 40 is $a <br />" );

// test if variable $a is 50 or less

if ( $a < 51 )

print( "Variable a is still 50 or less<br />" );

// test if variable $a is between 50 and 100, inclusive

elseif ( $a < 101 )

print( "Variable a is now between 50 and 100, inclusive<br />" );

else

print( "Variable a is now greater than 100<br />" );

 

// print an uninitialized variable

print( "Using a variable before initializing:

$nothing <br />" );

// add constant VALUE to an uninitialized variable

$test = $num + VALUE;

print( "An uninitialized variable plus constant

VALUE yields $test <br />" );

// add a string to an integer

$str = "3 dollars";

$a += $str;

print( "Adding a string to variable a yields $a

<br />" );

?>

Define function - constant VALUE

Referencing Operators We know the assignment operators work by value ,by copy the

value to other expression ,if the value in right hand change the value

in left is not change .

Ex:

<?php

$a =10;

$b =$a;

$b =20

Echo $a; // 10

?>

Referencing Operators

But we can change the value of variable $a by the reference , that

mena connect right hand to left hand ,

Example:

<?php

$a =10;

$b = &$a;

$b= 20;

echo $a; // 20

?>

PHP Conditional Statements

Very often when you write code, you want to perform different

actions for different decisions. You can use conditional

statements in your code to do this.

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 the condition is false

if...else if....else statement - selects one of several blocks of code to

be executed

switch statement - selects one of many blocks of code to be executed

The if Statement

• The if statement is used to execute some code only if a specified

condition is true.

<?php$t=5;if ($t<10)  {  echo "hello john";  }?>

hello john

if (condition)  {  code to be executed if condition is true;  }

The if...else Statement

• Use the if....else statement to execute some code if a condition is

true and another code if the condition is false.

if (condition) {  code to be executed if condition is true; }else {  code to be executed if condition is false; }

The if...else Statement

<?php$t=55;if ($t<20)  {  echo "Have a good day!";  }else  {  echo "Have a good night!";  }?>

Have a good night!

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

• Use the if....else if...else statement to select one of several blocks

of code to be executed. if (condition)  {  code to be executed if condition is true;  }else if (condition)  {  code to be executed if condition is true; }else  {  code to be executed if condition is false; }

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

<?php$t=7;if ($t<10) { echo "Have a good morning!"; }else if ($t<20) { echo "Have a good day!"; }else { echo "Have a good night!"; }?>

Have a good morning!

The switch Statement

• Use the switch statement to select one of many blocks of code to

be executed.

switch (n){case label1:  code to be executed if n=label1;  break;case label2:  code to be executed if n=label2;  break;default:  code to be executed if n is different from both label1 and label2;}

The switch Statement<?php$favcolor="red";switch ($favcolor){case "red":  echo "Your favorite color is red!";  break;case "blue":  echo "Your favorite color is blue!";  break;case "green":  echo "Your favorite color is green!";  break;default:  echo "Your favorite color is neither red, blue, or green!";}?>

Your favorite color is red!

PHP Loops

• Loops execute a block of code a specified number of times, or

while a specified condition is true.

• In PHP, we have the following looping statements:

• while - loops through a block of code while a specified

condition is true

• do...while - loops through a block of code once, and then

repeats the loop as long as a specified condition is true

• for - loops through a block of code a specified number of

times

• foreach - loops through a block of code for each element in

an array

The while Loop• The while loop executes a block of code while a condition is true.

while (condition)  {  code to be executed;  }

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

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

The do...while Statement

• The do...while statement will always execute the block of code

once, it will then check the condition, and repeat the loop while

the condition is true.

do  {  code to be executed;  }while (condition);<?php

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

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

The do...while Statement

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

The number is 3The number is 4The number is 5The number is 6

The for Loop

• The for loop is used when you know in advance how many times

the script should run.

• Parameters:

• init: Mostly used to set a counter (but can be any code to be

executed once at the beginning of the loop)

for (init; condition; increment)  {  code to be executed;  }

The for Loop

• condition: Evaluated for each loop iteration. If it

evaluates to TRUE, the loop continues. If it evaluates to

FALSE, the loop ends.

• increment: Mostly used to increment a counter (but

can be any code to be executed at the end of the

iteration)

• Note: The init and increment parameters above can

be empty or have multiple expressions (separated

by commas).

The for Loop

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

The number is 2The number is 3The number is 4The number is 5

The foreach Loop

• The foreach loop is used to loop through arrays.

• We well talk about this in chapter array

Isset Function

• bool isset (  $var )

• Determine if a variable is set and is not NULL.

• If a variable has been unset with unset(), it will no longer be

set. isset() will return FALSE if testing a variable that has been

set to NULL. Also note that 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 unset variable is

encountered.

Isset Function

<?php

$var = '';

// This will evaluate to TRUE so the text will be printed.

if (isset($var))

 {

    echo "This var is set so I will print.";

}

?>

Unset Function

• void unset ( $var)

• unset() destroys the specified variables.

• The behavior of unset() inside of a function can vary depending

on what type of variable you are attempting to destroy.

• 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 before unset() was called.

unset Function

<?php

$foo = 'bar';

echo $foo;

unset($foo);

echo $foo;

?>

Info PHP Page

<?php

phpinfo();

?>

Goto<?php

goto a;echo 'Foo'; a:echo 'Bar';?>

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

Chapter Example

if/else if/else statement

<?php

if ($foo == 0) {

echo ‘The variable foo is equal to 0’;

}

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

<?php$count=0;switch($count){

case 0:echo “hello PHP3. ”;

break;case 1:

echo “hello PHP4. ”;break; default:

echo “hello PHP5. ”;break;

}

?>

hello PHP3

Switch - Example<?php

$total = 0;

$i = 2;

switch($i) {

    case 6: $total = 99; break;

    case 1: $total += 1;break;

    case 2:$total += 2;break;

    case 3: $total += 3; ;break;

    case 4:$total += 4; break;

default : $total += 5;break;

}

echo $total;

?>

2

For Loop

<?php$count=0;for($count = 0;$count <3,$count++){

Print “hello PHP. ”;}?>

hello PHP. hello PHP. hello PHP.

For - Example

<?php

for ($i = 1; $i <= 10; $i++) {    echo $i;}

?>

For-Example

<?php$brush_price = 5; echo "<table border=\"1\" align=\"center\">"; echo "<tr><th>Quantity</th>"; echo "<th>Price</th></tr>";

for ( $counter = 10; $counter <= 100; $counter += 10) {

echo "<tr><td>"; echo $counter; echo "</td><td>"; echo $brush_price * $counter; echo "</td></tr>";

} echo "</table>";?>

While Loop

<?php$count=0;while($count<3){

echo “hello PHP. ”;$count += 1;// $count = $count + 1;// or// $count++;

}?>

hello PHP. hello PHP. hello PHP.

While - Example

<?php$i = 0;while ($i++ < 5)  {

echo “loop number : “.$i;    }

?>

Do ... While Loop

<?php$count=0;do{echo “hello PHP. ”;

$count += 1;// $count = $count + 1;// or// $count++;

}while($count<3);?>

hello PHP. hello PHP. hello PHP.

Do..While

<?php$i = 0;do {    echo $i;} while ($i > 0);?>

For..If

<?php

$rows = 4;

echo '<table><tr>';

for($i = 0; $i < 10; $i++){

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

    if(($i + 1) % $rows == 0){

        echo '</tr><tr>';

    }

}

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

?>

For

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

?>

Nested For

<?php for($a=0;$a<10;$a++){     for($b=0;$b<10;$b++){           for($c=0;$c<10;$c++){               for($d=0;$d<10;$d++){                 echo $a.$b.$c.$d.", ";               }            }       } } ?> 

While - Switch

<?php$i = 0;

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

Continue

<?phpfor ($i = 0; $i < 5; ++$i) {    if ($i == 2)        continue    print "$i\n";}?>

If - Switch<?php

$i = 1;if ($i == 0) {    echo "i equals 0";} elseif ($i == 1) {    echo "i equals 1";} elseif ($i == 2) {    echo "i equals 2";}

switch ($i) {    case 0:        echo "i equals 0";        break;    case 1:        echo "i equals 1";        break;    case 2:        echo "i equals 2";        break;}?>

Do..While - IF

<?phpdo {    if ($i < 5) {        echo "i is not big enough";        break;    }    $i *= $factor;    if ($i < $minimum_limit) {        break;    }   echo "i is ok";

    /* process i */

} while (0);?>

If in other style

<?php$hour = 11;

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

?>


Recommended