W1 PHP Tutorial
W1 PHP Tutorial
Chu-Cheng Hsieh
Agenda
Demo
Project 1A
Scripting block
First example
<html> <body> <?php echo "Hello World";
/* Im comment */
?> </body> </html>
5
Variable in PHP
does not need to be declared start with a letter or an underscore "_ alpha-numeric characters and underscores (a-Z, 0-9, and _ ) not contain spaces
String
<?php $txt1="Hello World"; $txt2="1234"; echo $txt1 . " " . $txt2; ?>
Operators
Arithmetic
Assignment
Comparison
Logical
A useful resource
http://us2.php.net/manual/en/
10
ifelse
if (condition)
elseif (condition)
else
11
example of if~else
<html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif ($d=="Sun") echo "Have a nice Sunday!"; else echo "Have a nice day!"; ?> </body> </html>
12
switch
<html> <body> <?php switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; } ?> </body> </html>
13
Arrays
14
Associative Arrays
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; Example
<?php
$ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; echo "Peter is " . $ages['Peter'] . " years old.";
15
?>
Looping ~ while
<html>
<body> <?php
$i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; }
?> </body>
</html>
16
Looping ~ for
functions
<html> <body>
<?php
function writeMyName() { echo "Kai Jim Refsnes"; }
echo "Hello world!<br />"; echo "My name is "; writeMyName(); echo ".<br />That's right, "; writeMyName(); echo " is my name.";
?>
</body> </html>
18
eval Example:
<html> <body>
<?php $equ = "3+4*5"; eval("\$ans = $equ ;"); echo "ans = ".$ans; ?> </body> </html>
20
preg_match
<html> <body> <? preg_match("/^(http:\/\/)?([^\/]+)/i", "http://www.php.net/index.html", $matches); print $host = $matches[0]."<BR>"; print $host = $matches[1]."<BR>"; print $host = $matches[2]."<BR>"; // get last two segments of host name preg_match("/[^\.\/]+\.[^\.\/]+$/","http://www.php.net",$matches); echo "domain name is: ".$matches[0]."\n"; ?> </body> </html>
21
matches
$matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.
22