SlideShare a Scribd company logo
1 of 19
Download to read offline
9/17/2014 
1 
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
9/17/2014 
2 
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!”; %>
9/17/2014 
3 
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)
9/17/2014 
4 
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."); 
?>
9/17/2014 
5 
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.
9/17/2014 
6 
PHP strings can be specified in four ways 
• Heredoc 
<?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': x41 
EOT; 
?> 
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': x41 
EOT; 
?> 
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)
9/17/2014 
7 
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; 
"Computer Science" 
echo $heading1; 
Computer Science 
?> 
Example 
<?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 
?> 
• 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 
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, 
True or false. 
Boolean 
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>"; 
?> 
integer 
double 
string
9/17/2014 
8 
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 
Now using type casting instead: 
As a string - 98.6 degrees 
As a double - 98.6 
As an integer - 98 
<?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; 
?> 
Casting Data type 
$variable = (datatype) $variable or value 
<?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; 
?> 
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
9/17/2014 
9 
PHP Operators 
• Arithmetic Operators 
• Assignment Operators 
• Incrementing/Decrementing Operators 
• Comparison Operators 
• Logical Operators 
Arithmetic Operators 
Operator 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 % 2 
10 % 8 
10 % 2 
1 
2 
0 
- 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 
<?php 
$a=15; 
$b=30; 
$total=$a+$b; 
echo $total; 
echo“<p><h1>$total</h1>”; 
// total is 45 
?> 
• $a - $b // subtraction 
• $a * $b // multiplication 
• $a / $b // division 
• $a += 5 // $a = $a+5 Also works for *= and /= 
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 
?>
9/17/2014 
10 
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 
void var_dump ($expression [,... ] ) 
• 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. 
<?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
9/17/2014 
11 
Logical Operators 
Operator Name Description Example 
x and y And True if both x and y are true x=6 
y=3 
(x < 10 and y > 1) returns true 
x or y Or True if either or both x and y are true x=6 
y=3 
(x==6 or y==5) returns true 
x xor y Xor True if either x or y is true, but not both x=6 
y=3 
(x==6 xor y==3) returns false 
x && y And True if both x and y are true x=6 
y=3 
(x < 10 && y > 1) returns true 
x || y Or True if either or both x and y are true x=6 
y=3 
(x==5 || y==5) returns false 
! x Not True if x is not true x=6 
y=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 
. 
<?php 
define(‘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 />" ); 
Define function - constant VALUE 
// 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 />" ); 
?>
9/17/2014 
12 
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!
9/17/2014 
13 
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; 
} 
The number is 1 
The number is 2 
The number is 3 
The number is 4 
The number is 5 
<?php 
$i=1; 
while($i<=5) 
{ 
echo "The number is " . $i . "<br>"; 
$i++; 
} 
?>
9/17/2014 
14 
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. 
d o 
{ 
code to be executed; 
} 
while (conditio<n?)p; hp 
$i=1; 
do 
{ 
$i++; 
echo "The number is " . $i . "<br>"; 
} 
while ($i<=5); 
?> 
The number is 2 
The number is 3 
The number is 4 
The number is 5 
The 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 3 
The number is 4 
The number is 5 
The number is 6 
The for Loop 
• The for loop is used when you know in advance how many times the script should 
run. 
for (init; condition; increment) 
{ 
code to be executed; 
} 
• Parameters: 
• 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 
• 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 
<?php 
for ($i=1; $i<=5; $i++) 
{ 
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 
The foreach Loop 
• The foreach loop is used to loop through arrays. 
• We well talk about this in chapter array
9/17/2014 
15 
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'; 
?> 
<?php 
for($i=0,$j=50; $i<100; $i++) { 
while($j--) { 
if($j==17) goto end; 
} 
} 
echo "i = $i"; 
end: 
echo 'j hit 17'; 
?>
9/17/2014 
16 
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; 
} 
?>
9/17/2014 
17 
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>'; 
?>
9/17/2014 
18 
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 
<?php 
for ($i = 0; $i < 5; ++$i) { 
if ($i == 2) 
continue 
print "$in"; 
} 
?> 
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 
<?php 
do { 
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); 
?>
9/17/2014 
19 
If in other style 
<?php 
$hour = 11; 
echo $foo = ($hour < 12) ? "Good morning!" : "Good 
afternoon!"; 
?>

More Related Content

What's hot (20)

Introduction to php php++
Introduction to php php++Introduction to php php++
Introduction to php php++
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
php app development 1
php app development 1php app development 1
php app development 1
 
Welcome to computer programmer 2
Welcome to computer programmer 2Welcome to computer programmer 2
Welcome to computer programmer 2
 
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
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Php introduction and configuration
Php introduction and configurationPhp introduction and configuration
Php introduction and configuration
 
Server Scripting Language -PHP
Server Scripting Language -PHPServer Scripting Language -PHP
Server Scripting Language -PHP
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Php Unit 1
Php Unit 1Php Unit 1
Php Unit 1
 
PHP slides
PHP slidesPHP slides
PHP slides
 
Dev traning 2016 basics of PHP
Dev traning 2016   basics of PHPDev traning 2016   basics of PHP
Dev traning 2016 basics of PHP
 
Intro to php
Intro to phpIntro to php
Intro to php
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
 
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
 
Prersentation
PrersentationPrersentation
Prersentation
 
PHP - Introduction to PHP Fundamentals
PHP -  Introduction to PHP FundamentalsPHP -  Introduction to PHP Fundamentals
PHP - Introduction to PHP Fundamentals
 
Constructor and encapsulation in php
Constructor and encapsulation in phpConstructor and encapsulation in php
Constructor and encapsulation in php
 

Viewers also liked

Membuat Website PHP Metode CRUD
Membuat Website PHP Metode CRUDMembuat Website PHP Metode CRUD
Membuat Website PHP Metode CRUDRobby Firmansyah
 
South-South Cooperation seminar outline
South-South Cooperation seminar outline South-South Cooperation seminar outline
South-South Cooperation seminar outline futureagricultures
 
Aberdeen ppt-iam integrated-db-06 20120412
Aberdeen ppt-iam integrated-db-06 20120412Aberdeen ppt-iam integrated-db-06 20120412
Aberdeen ppt-iam integrated-db-06 20120412OracleIDM
 
Appeared in new york times yesterday
Appeared in new york times yesterdayAppeared in new york times yesterday
Appeared in new york times yesterdayAbhishek Saha
 
Ig2 assignment brief_updated_27.04.12
Ig2 assignment brief_updated_27.04.12Ig2 assignment brief_updated_27.04.12
Ig2 assignment brief_updated_27.04.12FirstClassProductions
 
Introduction to videoconferencing in schools
Introduction to videoconferencing in schoolsIntroduction to videoconferencing in schools
Introduction to videoconferencing in schoolsEleanor Schuster
 
Extraclase de ingles !!!
Extraclase de ingles !!!Extraclase de ingles !!!
Extraclase de ingles !!!teacherisela
 
Summer workshop_GROUP3_20110714_presentation
Summer workshop_GROUP3_20110714_presentationSummer workshop_GROUP3_20110714_presentation
Summer workshop_GROUP3_20110714_presentationludan1211
 
Acids & Bases Day 1
Acids & Bases   Day 1Acids & Bases   Day 1
Acids & Bases Day 1jmori1
 
Report on OAS Round Table on Indigenous Trade and Development: Case Study of...
Report on OAS Round Table on Indigenous Trade and Development:  Case Study of...Report on OAS Round Table on Indigenous Trade and Development:  Case Study of...
Report on OAS Round Table on Indigenous Trade and Development: Case Study of...Wayne Dunn
 
Аллергические заболевания слизистой оболочки полости рта у детей
Аллергические заболевания слизистой оболочки полости рта у детейАллергические заболевания слизистой оболочки полости рта у детей
Аллергические заболевания слизистой оболочки полости рта у детейcrasgmu
 

Viewers also liked (20)

Processor CPU
Processor CPUProcessor CPU
Processor CPU
 
Modul I/O by MRobbyF
Modul I/O by MRobbyFModul I/O by MRobbyF
Modul I/O by MRobbyF
 
Gerbang Logika
Gerbang LogikaGerbang Logika
Gerbang Logika
 
M robby f_mi2b_tugas 2
M robby f_mi2b_tugas 2M robby f_mi2b_tugas 2
M robby f_mi2b_tugas 2
 
Rational Unified Process
Rational Unified ProcessRational Unified Process
Rational Unified Process
 
Subnetting
SubnettingSubnetting
Subnetting
 
UseCase Diagram
UseCase DiagramUseCase Diagram
UseCase Diagram
 
Membuat Website PHP Metode CRUD
Membuat Website PHP Metode CRUDMembuat Website PHP Metode CRUD
Membuat Website PHP Metode CRUD
 
Internal memory
Internal memoryInternal memory
Internal memory
 
South-South Cooperation seminar outline
South-South Cooperation seminar outline South-South Cooperation seminar outline
South-South Cooperation seminar outline
 
Aberdeen ppt-iam integrated-db-06 20120412
Aberdeen ppt-iam integrated-db-06 20120412Aberdeen ppt-iam integrated-db-06 20120412
Aberdeen ppt-iam integrated-db-06 20120412
 
Appeared in new york times yesterday
Appeared in new york times yesterdayAppeared in new york times yesterday
Appeared in new york times yesterday
 
Ig2 assignment brief_updated_27.04.12
Ig2 assignment brief_updated_27.04.12Ig2 assignment brief_updated_27.04.12
Ig2 assignment brief_updated_27.04.12
 
Introduction to videoconferencing in schools
Introduction to videoconferencing in schoolsIntroduction to videoconferencing in schools
Introduction to videoconferencing in schools
 
Extraclase de ingles !!!
Extraclase de ingles !!!Extraclase de ingles !!!
Extraclase de ingles !!!
 
Summer workshop_GROUP3_20110714_presentation
Summer workshop_GROUP3_20110714_presentationSummer workshop_GROUP3_20110714_presentation
Summer workshop_GROUP3_20110714_presentation
 
Informator oswiatowy
Informator oswiatowyInformator oswiatowy
Informator oswiatowy
 
Acids & Bases Day 1
Acids & Bases   Day 1Acids & Bases   Day 1
Acids & Bases Day 1
 
Report on OAS Round Table on Indigenous Trade and Development: Case Study of...
Report on OAS Round Table on Indigenous Trade and Development:  Case Study of...Report on OAS Round Table on Indigenous Trade and Development:  Case Study of...
Report on OAS Round Table on Indigenous Trade and Development: Case Study of...
 
Аллергические заболевания слизистой оболочки полости рта у детей
Аллергические заболевания слизистой оболочки полости рта у детейАллергические заболевания слизистой оболочки полости рта у детей
Аллергические заболевания слизистой оболочки полости рта у детей
 

Similar to Materi Dasar PHP

php Chapter 1.pptx
php Chapter 1.pptxphp Chapter 1.pptx
php Chapter 1.pptxHambaAbebe2
 
php basic part one
php basic part onephp basic part one
php basic part onejeweltutin
 
Php tutorial from_beginner_to_master
Php tutorial from_beginner_to_masterPhp tutorial from_beginner_to_master
Php tutorial from_beginner_to_masterPrinceGuru MS
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)Arjun Shanka
 
Hsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdfHsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdfAAFREEN SHAIKH
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...anshkhurana01
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPwahidullah mudaser
 
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 Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics EbookSwanand Pol
 

Similar to Materi Dasar PHP (20)

php Chapter 1.pptx
php Chapter 1.pptxphp Chapter 1.pptx
php Chapter 1.pptx
 
php basic part one
php basic part onephp basic part one
php basic part one
 
Php tutorial from_beginner_to_master
Php tutorial from_beginner_to_masterPhp tutorial from_beginner_to_master
Php tutorial from_beginner_to_master
 
Php tutorialw3schools
Php tutorialw3schoolsPhp tutorialw3schools
Php tutorialw3schools
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Php unit i
Php unit iPhp unit i
Php unit i
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Hsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdfHsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdf
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
 
Php
PhpPhp
Php
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
PHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERSPHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERS
 
Introduction to-php
Introduction to-phpIntroduction to-php
Introduction to-php
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics Ebook
 
phptutorial
phptutorialphptutorial
phptutorial
 
phptutorial
phptutorialphptutorial
phptutorial
 

More from Robby Firmansyah

More from Robby Firmansyah (20)

Dokumentasi Postfix
Dokumentasi PostfixDokumentasi Postfix
Dokumentasi Postfix
 
Dokumentasi Webmin
Dokumentasi WebminDokumentasi Webmin
Dokumentasi Webmin
 
Skenario
SkenarioSkenario
Skenario
 
Activity Diagram
Activity DiagramActivity Diagram
Activity Diagram
 
Network Interface Layer
Network Interface LayerNetwork Interface Layer
Network Interface Layer
 
Dokumentasi Gammu
Dokumentasi GammuDokumentasi Gammu
Dokumentasi Gammu
 
Moodle - Kuisioner
Moodle - KuisionerMoodle - Kuisioner
Moodle - Kuisioner
 
Ppt moodle sip
Ppt moodle sipPpt moodle sip
Ppt moodle sip
 
Cara menghubungkan Database antar PC
Cara menghubungkan Database antar PCCara menghubungkan Database antar PC
Cara menghubungkan Database antar PC
 
Network Troubleshooting
Network TroubleshootingNetwork Troubleshooting
Network Troubleshooting
 
Setting FTP, SSH, NsLookup di linux
Setting FTP, SSH, NsLookup di linuxSetting FTP, SSH, NsLookup di linux
Setting FTP, SSH, NsLookup di linux
 
Rangkuman Addressing
Rangkuman AddressingRangkuman Addressing
Rangkuman Addressing
 
Pengenalan RPL
Pengenalan RPLPengenalan RPL
Pengenalan RPL
 
Rangkuman SDLC
Rangkuman SDLCRangkuman SDLC
Rangkuman SDLC
 
Rangkuman DBMS
Rangkuman DBMSRangkuman DBMS
Rangkuman DBMS
 
Tutorial Install SQL SERVER 2008
Tutorial Install SQL SERVER 2008Tutorial Install SQL SERVER 2008
Tutorial Install SQL SERVER 2008
 
Konsep Sistem Manajemen BasisData
Konsep Sistem Manajemen BasisDataKonsep Sistem Manajemen BasisData
Konsep Sistem Manajemen BasisData
 
Materi 4 String dan Boolean Expression
Materi 4 String dan Boolean ExpressionMateri 4 String dan Boolean Expression
Materi 4 String dan Boolean Expression
 
Materi 3 Coding dan Testing aplikasi
Materi 3 Coding dan Testing aplikasiMateri 3 Coding dan Testing aplikasi
Materi 3 Coding dan Testing aplikasi
 
Materi 1 Pemrograman berbasis GUI
Materi 1 Pemrograman berbasis GUIMateri 1 Pemrograman berbasis GUI
Materi 1 Pemrograman berbasis GUI
 

Recently uploaded

Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxAneriPatwari
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 

Recently uploaded (20)

Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 

Materi Dasar PHP

  • 1. 9/17/2014 1 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
  • 2. 9/17/2014 2 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!”; %>
  • 3. 9/17/2014 3 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)
  • 4. 9/17/2014 4 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."); ?>
  • 5. 9/17/2014 5 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.
  • 6. 9/17/2014 6 PHP strings can be specified in four ways • Heredoc <?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': x41 EOT; ?> 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': x41 EOT; ?> 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)
  • 7. 9/17/2014 7 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; "Computer Science" echo $heading1; Computer Science ?> Example <?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 ?> • 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 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, True or false. Boolean 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>"; ?> integer double string
  • 8. 9/17/2014 8 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 Now using type casting instead: As a string - 98.6 degrees As a double - 98.6 As an integer - 98 <?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; ?> Casting Data type $variable = (datatype) $variable or value <?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; ?> 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
  • 9. 9/17/2014 9 PHP Operators • Arithmetic Operators • Assignment Operators • Incrementing/Decrementing Operators • Comparison Operators • Logical Operators Arithmetic Operators Operator 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 % 2 10 % 8 10 % 2 1 2 0 - 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 <?php $a=15; $b=30; $total=$a+$b; echo $total; echo“<p><h1>$total</h1>”; // total is 45 ?> • $a - $b // subtraction • $a * $b // multiplication • $a / $b // division • $a += 5 // $a = $a+5 Also works for *= and /= 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 ?>
  • 10. 9/17/2014 10 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 void var_dump ($expression [,... ] ) • 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. <?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
  • 11. 9/17/2014 11 Logical Operators Operator Name Description Example x and y And True if both x and y are true x=6 y=3 (x < 10 and y > 1) returns true x or y Or True if either or both x and y are true x=6 y=3 (x==6 or y==5) returns true x xor y Xor True if either x or y is true, but not both x=6 y=3 (x==6 xor y==3) returns false x && y And True if both x and y are true x=6 y=3 (x < 10 && y > 1) returns true x || y Or True if either or both x and y are true x=6 y=3 (x==5 || y==5) returns false ! x Not True if x is not true x=6 y=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 . <?php define(‘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 />" ); Define function - constant VALUE // 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 />" ); ?>
  • 12. 9/17/2014 12 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!
  • 13. 9/17/2014 13 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; } The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br>"; $i++; } ?>
  • 14. 9/17/2014 14 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. d o { code to be executed; } while (conditio<n?)p; hp $i=1; do { $i++; echo "The number is " . $i . "<br>"; } while ($i<=5); ?> The number is 2 The number is 3 The number is 4 The number is 5 The 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 3 The number is 4 The number is 5 The number is 6 The for Loop • The for loop is used when you know in advance how many times the script should run. for (init; condition; increment) { code to be executed; } • Parameters: • 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 • 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 <?php for ($i=1; $i<=5; $i++) { 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 The foreach Loop • The foreach loop is used to loop through arrays. • We well talk about this in chapter array
  • 15. 9/17/2014 15 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'; ?> <?php for($i=0,$j=50; $i<100; $i++) { while($j--) { if($j==17) goto end; } } echo "i = $i"; end: echo 'j hit 17'; ?>
  • 16. 9/17/2014 16 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; } ?>
  • 17. 9/17/2014 17 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>'; ?>
  • 18. 9/17/2014 18 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 <?php for ($i = 0; $i < 5; ++$i) { if ($i == 2) continue print "$in"; } ?> 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 <?php do { 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); ?>
  • 19. 9/17/2014 19 If in other style <?php $hour = 11; echo $foo = ($hour < 12) ? "Good morning!" : "Good afternoon!"; ?>