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
Materi dasar tentang PHP pada matakuliah Pemrograman Web di Semester 3
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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
• 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;
echo $heading1;
?>
"Computer Science" Computer Science
Example
• Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25
• Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP
• This is true for both variables and character escape-sequences (such as “\n” or “\\”)
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
echo $bar; // Outputs Hello
echo $foo,$bar; // Outputs 25Hello
echo “5x5=”,$foo; // Outputs 5x5=25
echo “5x5=$foo”; // Outputs 5x5=25
echo ‘5x5=$foo’; // Outputs 5x5=$foo
?>
Data type
Data type Description int,
integer Whole numbers (i.e., numbers without a decimal point).
float, double
Real numbers (i.e., numbers containing a decimal point).
string Text enclosed in either single ('') or double ("") quotes. bool,
Boolean True or false.
array Group of elements of the same type. object Group of associated data and methods.
settype($foo, "integer"); // $foo is now 5 (integer)
settype($bar, "string"); // $bar is now "1" (string)
?>
Set type <?php
$testString = “10.2abc”;
// call function settype to convert variable
// testString to different data types
print( "$testString" );
settype( $testString, "double" );
print( " as a double is $testString <br />" );
print( "$testString" );
settype( $testString, "integer" );
print( " as an integer is $testString <br />" );
settype( $testString, "string" );
print( "Converting back to a string results in
$testString <br /><br />" );
?>
10.2abc as a double is 10.2 10.2 as an integer is 10 Converting back to a string results in 10
Casting Data type
<?php
$data = "98.6 degrees";
echo "Now using type casting instead: <br>";
echo "As a string - ".(string) $data ;
echo "<br> As a double - ".(double) $data;
echo "<br> As an integer - ".(integer) $data;
?>
Now using type casting instead: As a string - 98.6 degrees As a double - 98.6 As an integer - 98
Casting Data type
<?php
$data = "98.6 degrees";
echo "Now using type casting instead: <br>";
echo "As a string - ".(string) $data ;
echo "<br> As a double - ".(double) $data;
echo "<br> As an integer - ".(integer) $data;
?>
$variable = (datatype) $variable or value
Casting Data type
<?php
$a = “ 12.4 abc”
echo (int) $a;
echo (double) ($a);
echo (float) ($a);
echo (string) ($a);
?>
PHP Operators
• The assignment operator = is used to assign values to variables in PHP.
• The arithmetic operator + is used to add values together in PHP.
• Assignment operators Syntactical shortcuts
Before being assigned values, variables have value undef
• Constants Named values
define function
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
• $a - $b // subtraction
• $a * $b // multiplication
• $a / $b // division
• $a += 5 // $a = $a+5 Also works for *= and /=
<?php $a=15; $b=30; $total=$a+$b; echo $total;
echo“<p><h1>$total</h1>”;
// total is 45 ?>
Incrementing/Decrementing Operators
Operator Name Description
++ x Pre-increment Increments x by one, then returns x
x ++ Post-increment Returns x, then increments x by one
-- x Pre-decrement Decrements x by one, then returns x
x -- Post-decrement Returns x, then decrements x by one
Arithmetic Operations
<?php
$a =1; echo $a++; // output 1,$a is now equal to 2 echo ++$a; // output 3,$a is now equal to 3 echo --$a; // output 2,$a is now equal to 2 echo $a--; // output 2,$a is now equal to 1
?>
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
• This function displays structured information about one or more expressions that
includes its type and value. Arrays and objects are explored recursively with values
print( "Multiplying variable a by 2 yields $a <br />" );
// test if variable $a is less than 50
if ( $a < 50 )
print( "Variable a is less than 50 <br />" );
// add 40 to variable $a
$a += 40;
print( "Variable a after adding 40 is $a <br />" );
// test if variable $a is 50 or less
if ( $a < 51 )
print( "Variable a is still 50 or less<br />" );
// test if variable $a is between 50 and 100, inclusive
elseif ( $a < 101 )
print( "Variable a is now between 50 and 100, inclusive<br />" );
else
print( "Variable a is now greater than 100<br />" );
// print an uninitialized variable
print( "Using a variable before initializing:
$nothing <br />" );
// add constant VALUE to an uninitialized variable
$test = $num + VALUE;
print( "An uninitialized variable plus constant
VALUE yields $test <br />" );
// add a string to an integer
$str = "3 dollars";
$a += $str;
print( "Adding a string to variable a yields $a
<br />" );
?>
Define function - constant VALUE
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; }
<?php $i=1; while($i<=5) { echo "The number is " . $i . "<br>"; $i++; } ?>
The number is 1 The number is 2 The number is 3 The number is 4 The number is 5
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.
do { code to be executed; } while (condition);
<?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 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.
• Parameters:
• init: Mostly used to set a counter (but can be any code to be executed once at
the beginning of the loop)
for (init; condition; increment) { code to be executed; }
The for Loop
• condition: Evaluated for each loop iteration. If it evaluates to TRUE,
the loop continues. If it evaluates to FALSE, the loop ends.
• increment: Mostly used to increment a counter (but can be any code
to be executed at the end of the iteration)
• Note: The init and increment parameters above can be empty or
have multiple expressions (separated by commas).
The for Loop
<?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
<?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 />"; } ?>
$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 "$i\n"; } ?>
If - Switch <?php
$i = 1; if ($i == 0) { echo "i equals 0"; } elseif ($i == 1) { echo "i equals 1"; } elseif ($i == 2) { echo "i equals 2"; } switch ($i) { case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; } ?>
Do..While - IF
<?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); ?>