SlideShare a Scribd company logo
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

PPSX
PHP Comprehensive Overview
PDF
Php a dynamic web scripting language
PPTX
PPTX
Php basics
PPT
Introduction to PHP - SDPHP
PDF
Php tutorial
PHP Comprehensive Overview
Php a dynamic web scripting language
Php basics
Introduction to PHP - SDPHP
Php tutorial

What's hot (20)

PPT
Introduction to php php++
PDF
Introduction to php
KEY
php app development 1
PPTX
Welcome to computer programmer 2
PDF
1336333055 php tutorial_from_beginner_to_master
PPTX
Basic of PHP
PPTX
Php introduction and configuration
PPTX
Server Scripting Language -PHP
PPTX
Php Tutorial
PDF
Introduction to php
PPTX
Php Unit 1
PPTX
PHP slides
PPTX
Dev traning 2016 basics of PHP
PPTX
Intro to php
PPT
Control Structures In Php 2
PPT
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
PPT
Prersentation
PPT
PHP - Introduction to PHP Fundamentals
PPTX
Constructor and encapsulation in php
Introduction to php php++
Introduction to php
php app development 1
Welcome to computer programmer 2
1336333055 php tutorial_from_beginner_to_master
Basic of PHP
Php introduction and configuration
Server Scripting Language -PHP
Php Tutorial
Introduction to php
Php Unit 1
PHP slides
Dev traning 2016 basics of PHP
Intro to php
Control Structures In Php 2
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Prersentation
PHP - Introduction to PHP Fundamentals
Constructor and encapsulation in php
Ad

Viewers also liked (20)

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

Similar to Materi Dasar PHP (20)

PPTX
Php by shivitomer
DOCX
Basic php 5
DOCX
PHP NOTES FOR BEGGINERS
PDF
WT_PHP_PART1.pdf
PPTX
Php unit i
PPTX
PHP stand for PHP Hypertext Preprocessor
PPTX
Introduction to php
PDF
Introduction to PHP - Basics of PHP
PDF
PHP in Web development and Applications.pdf
PDF
Lecture2_IntroductionToPHP_Spring2023.pdf
PDF
Web Development Course: PHP lecture 1
PPTX
introduction to php and its uses in daily
PPTX
PPTX
PHP Training Part1
PPTX
The basics of php for engeneering students
PDF
Introduction to PHP_Slides by Lesley_Bonyo.pdf
PPTX
Php intro
PPTX
php Chapter 1.pptx
PPTX
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php by shivitomer
Basic php 5
PHP NOTES FOR BEGGINERS
WT_PHP_PART1.pdf
Php unit i
PHP stand for PHP Hypertext Preprocessor
Introduction to php
Introduction to PHP - Basics of PHP
PHP in Web development and Applications.pdf
Lecture2_IntroductionToPHP_Spring2023.pdf
Web Development Course: PHP lecture 1
introduction to php and its uses in daily
PHP Training Part1
The basics of php for engeneering students
Introduction to PHP_Slides by Lesley_Bonyo.pdf
Php intro
php Chapter 1.pptx
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...

More from Robby Firmansyah (20)

DOCX
Dokumentasi Postfix
DOCX
Dokumentasi Webmin
PPTX
PPT
Activity Diagram
PPTX
Network Interface Layer
DOCX
Dokumentasi Gammu
PPTX
Moodle - Kuisioner
PPTX
Ppt moodle sip
DOCX
Cara menghubungkan Database antar PC
DOCX
Network Troubleshooting
DOCX
Setting FTP, SSH, NsLookup di linux
DOCX
Rangkuman Addressing
PPTX
Pengenalan RPL
DOCX
Rangkuman SDLC
DOCX
Rangkuman DBMS
DOCX
Tutorial Install SQL SERVER 2008
DOCX
Konsep Sistem Manajemen BasisData
PPTX
Materi 4 String dan Boolean Expression
PPTX
Materi 3 Coding dan Testing aplikasi
PPTX
Materi 1 Pemrograman berbasis GUI
Dokumentasi Postfix
Dokumentasi Webmin
Activity Diagram
Network Interface Layer
Dokumentasi Gammu
Moodle - Kuisioner
Ppt moodle sip
Cara menghubungkan Database antar PC
Network Troubleshooting
Setting FTP, SSH, NsLookup di linux
Rangkuman Addressing
Pengenalan RPL
Rangkuman SDLC
Rangkuman DBMS
Tutorial Install SQL SERVER 2008
Konsep Sistem Manajemen BasisData
Materi 4 String dan Boolean Expression
Materi 3 Coding dan Testing aplikasi
Materi 1 Pemrograman berbasis GUI

Recently uploaded (20)

PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
PPTX
Revamp in MTO Odoo 18 Inventory - Odoo Slides
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Cell Structure & Organelles in detailed.
PDF
Pre independence Education in Inndia.pdf
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PPTX
Pharma ospi slides which help in ospi learning
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Introduction and Scope of Bichemistry.pptx
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
Module 3: Health Systems Tutorial Slides S2 2025
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
PDF
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
PDF
From loneliness to social connection charting
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
Revamp in MTO Odoo 18 Inventory - Odoo Slides
Abdominal Access Techniques with Prof. Dr. R K Mishra
Cell Structure & Organelles in detailed.
Pre independence Education in Inndia.pdf
The Final Stretch: How to Release a Game and Not Die in the Process.
Pharma ospi slides which help in ospi learning
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Anesthesia in Laparoscopic Surgery in India
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Introduction and Scope of Bichemistry.pptx
Week 4 Term 3 Study Techniques revisited.pptx
Module 3: Health Systems Tutorial Slides S2 2025
Open Quiz Monsoon Mind Game Final Set.pptx
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
From loneliness to social connection charting
O7-L3 Supply Chain Operations - ICLT Program
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
UNDER FIVE CLINICS OR WELL BABY CLINICS.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!"; ?>