php basics examples taken from: beginning php 5 and mysql 5 from novice to professional

109
PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Upload: marvin-porter

Post on 24-Dec-2015

220 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

PHP Basics

Examples taken from:Beginning PHP 5 and MySQL 5

From Novice to Professional

Page 2: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

hello.php

<html><head><title>PHP Test</title></head><body><?php echo '<p>Hello PHP World</p>'; ?></body></html>

Page 3: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

current-date.php

<?php echo date("F j, Y");?>

• Note script – not enclosed in HTML code– does not have execute permision on server– very compact– can be cryptic

Page 4: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Default SyntaxPHP code delimiters

• <h3>Welcome!</h3>• <?php• print "<p>This is a PHP example.</p>";• ?>• <p>Some static information found here...</p>

Page 5: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Short Syntax

<?print "This is another PHP example.";?><?="This is another PHP example.";?><? print "This is another PHP example."; ?>

• Note short tag delimiters– may conflict with XML. – Requires short_open_tag directive

Page 6: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Editor Syntax

<script language="php">print "This is another PHP example.";</script>

• Note – used by some HTML editors (ie. FrontPage) that have problems dealing with the PHP escape syntax.

Page 7: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

ASP-Style

<%print "This is another PHP example.";%>

• Note - Microsoft ASP pages use a predefined character pattern to open/close dynamic syntax that is supported by PHP.

Page 8: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Multiple Code Blocks<html><head><title><?php echo "Welcome to my site!";?></title></head><body><?php$date = "May 18, 2003";?><h3>Today's date is <?=$date;?></h3></body></html>

• Note that variable values persist between blocks.

Page 9: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

PHP CommentsShell Syntax

<?php# Title: My PHP program# Author: Jasonprint "This is a PHP program";?>

Page 10: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

PHP CommentsC Syntax

<?php# Title: My PHP program# Author: Jasonprint "This is a PHP program";?>

Page 11: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

PHP CommentsMulti-line C Syntax

<?php/*Title: My PHP ProgramAuthor: JasonDate: October 10, 2005*/?>

Page 12: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

boolean print (argument)<?phpprint("<p>I love the summertime.</p>");?>

<?php$season = "summertime";print "<p>I love the $season.</p>";?>

<?phpprint "<p>I love thesummertime.</p>";?>

<?php$season = "summertime";print "<p>I love the ".$season."</p>";?>

Page 13: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Print()

• On the examples just given did you note that:– The parentheses to enclose the argument are

optional.– The how concatenation was used in the last

example.

Page 14: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

void echo (string argument1 [, ...string argumentN])

<?php$heavyweight = "Lennox Lewis";$lightweight = "Floyd Mayweather";echo $heavyweight, " and ", $lightweight, " are

great fighters.";?>

Page 15: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

boolean printf (string format [, mixed args])

printf("$%01.2f", 43.2); // $43.20

printf("%d beer %s", 100, "bottles"); // 100 beer bottles

printf("%15s", "Some text"); // Some text

Page 16: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

string sprintf (string format [, mixed arguments])

• Works like printf() but output is assigned to a string instead of directly to standard output

$cost = sprintf("$%01.2f", 43.2); // $cost = $43.20

Page 17: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Scalar Datatypes

• Boolean• Integer• Float• String

Page 18: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Boolean

$alive = false; # $alive is false.$alive = 1; # $alive is true.$alive = -1; # $alive is true.$alive = 5; # $alive is true.$alive = 0; # $alive is false.

• Note any non-zero value is TRUE.

Page 19: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Integer

42 # decimal-678900 # decimal0755 # octal0xC4E # hexadecimal• Note – if you exceed maxint PHP will

automatically convert the value to a float.

Page 20: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

String

• Historically PHP treated strings as arrays of characters

$color = "maroon";echo $color[2]; // outputs 'r‘

• PHP 5 introduces specialized string offset functionality

Page 21: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Compound Datatypes

• Array• Object

Page 22: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Array

Traditional Index$state[0] = "Alabama";$state[1] = "Alaska";$state[2] = "Arizona";...$state[49] = "Wyoming";

Associative Index• $state["Alabama"] =

"Montgomery";• $state["Alaska"] = "Juneau";• $state["Arizona"] = "Phoenix";• ...• $state["Wyoming"] =

"Cheyenne";

Page 23: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Object

class appliance {private $power;function setPower($status) {$this->power = $status;}}...$blender = new appliance;• Note – an object must be explicitly declared in PHP.

Page 24: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Special Datatypes

• Resource• Null

Page 25: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Resource

• Typically used to create variables for using resources, handles.

$fh = fopen("/home/jason/books.txt", "r");

Page 26: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Null

• Means that a value has not been assigned. In PHP, a value is null if:

• It has not been set to any predefined value.• It has been specifically assigned the value Null.• It has been erased using the function unset().• The null datatype recognizes only one value, Null:<?php$default = Null;?>

Page 27: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Type Casting

• Forces a variable to behave as a type other that the one originally indended.

$variable1 = 13;$variable2 = (double) $variable1; // $variable2 is assigned the value 13.0

$variable1 = 4.7;$variable2 = 5;$variable3 = (int) $variable1 + $variable2; // $variable3 = 9

Page 28: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Weakly typed withon-the-fly “best guess” type conversion

<?php$number = "5"; # $number is a string$sum = 15 + $number; # Add an integer and # string to produce integer$sum = "twenty"; # Overwrite $sum with a string.?>

Page 29: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Conversion to Boolean

<?php$total = "1.0";if ($total) echo "The total count is positive";?>• Note – $total is converted to type Boolean for the if

statement– You may see this often in PHP code

Page 30: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Type Related Functions

• boolean settype (mixed var, string type)– Converts the variable var to the datatype type– Type can be array, boolean, float, inteter, null,

object, or string• string gettype (mixed var)– Returns the datatype of the variable var– The return value can be array, boolean, double,

integer, object, resource, string, or unknown.

Page 31: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Type Identifier Functions

• boolean is_array (mixed var)• boolean is_bool (mixed var)• boolean is_float (mixed var)• boolean is_integer (mixed var)• boolean is_null (mixed var)• boolean is_numeric (mixed var)• boolean is_object (mixed var)• boolean is_resource (mixed var)• boolean is_scalar (mixed var)• boolean is_string (mixed var)

Page 32: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Identifiers

• An identifier can consist of one or more characters and must begin with a letter or an underscore.

• Identifiers can consist of only letters, numbers, underscore characters, and other ASCII characters from 127 through 255.

• Identifiers are case sensitive• Identifiers can be any length• Identifier names can be the same as PHP

predefined keywords.

Page 33: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Variables

• A variable name always begins with a dollar sign, $, then followed by the variable name.

• Variable names follow the same naming rules as identifiers.

• Variables do not have to be explicitly declared

Page 34: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Variable Assignment by Value

$color = "red";$number = 12;$age = 12;$sum = 12 + "15"; /* $sum = 27 */

• Note $number and $age reference two different memory locations.

Page 35: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Variable Assignment by Reference<?php$value1 = "Hello";$value2 =& $value1; /* $value1 and $value2 both equal "Hello". */$value2 = "Goodbye"; /* $value1 and $value2 both equal "Goodbye". */?>

• Note– $value1 and $value2 refer to the same memory location– You assign variables by reference by appending an ampersand (&) to

the equal sign.

Page 36: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Another Variable Assignment by Reference

<?php$value1 = "Hello";$value2 = &$value1; /* $value1 and $value2 both equal "Hello". */$value2 = "Goodbye"; /* $value1 and $value2 both equal "Goodbye". */?>

• Note – place the ampersand in front of the variable being referneced.

Page 37: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Variable Scope

• Local variables• Function parameters• Global variables• Static variables

Page 38: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Local Variables

• A variable declared in a function is considered local. That is, it can be referenced only in that function.

• Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function.

• When you exit the function in which a local variable has been declared, that variable and its corresponding value are destroyed.

Page 39: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Local Variable Example

$x = 4;function assignx () {$x = 0;print "\ $x inside function is $x. <br>";}assignx();print "\ $x outside of function is $x. <br>";

Page 40: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Function Parameters

• Any function that accepts arguments must declare those arguments in the function header.

• Although those arguments accept values that come from outside of the function, they are no longer accessible once the function has exited.

Page 41: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Function Parameter Example

// multiply a value by 10 and return it to the caller

function x10 ($value) {$value = $value * 10;return $value;}

Page 42: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Global Variables

• A global variable can be accessed in any part of the program.

• A global variable it must be explicitly declared to be global in the function in which it is to be modified.

• This is accomplished by placing the keyword GLOBAL in front of the variable that should be recognized as global.

• Placing this keyword in front of an already existing variable tells PHP to use the variable having that name.

Page 43: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Global Variable Example

$somevar = 15;function addit() {GLOBAL $somevar;$somevar++;print "Somevar is $somevar";}addit();

Page 44: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Global Variable Exampleusing PHP’s $GLOBALS array

$somevar = 15;function addit() {$GLOBALS["somevar"]++;}addit();print "Somevar is ".$GLOBALS["somevar"];

Page 45: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Static Variables

• A static variable does not lose its value when the function exits, and will still hold that value if the function is called again.

• You can declare a variable as static by placing the keyword STATIC in front of the variable name

Page 46: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Static Variable Example

function keep_track() {STATIC $count = 0;$count++;print $count;print "<br>";}keep_track();keep_track();keep_track();

Page 47: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

PHP’S Superglobal Variables

• Predefined variables that contain environment-specific information.

• $_SERVER• $_GET• $_POST• $_COOKIE• $_FILES• $_ENV• $_REQUEST• $_SESSION• $_GLOBALS

Page 48: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

$_SERVER

• Contains information created by the Web server.• the following• The following code will output all predefined

variables pertinent to any given Web server and the script’s execution environment:

foreach ($_SERVER as $var => $value) {echo "$var => $value <br />";}

Page 49: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

$_SERVER examples

print "Hi! Your IP address is: $_SERVER['REMOTE_ADDR']";

print "Your browser is: $_SERVER['HTTP_USER_AGENT']";

Page 50: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

$_GET

• Contains information pertinent to any parameters passed using the GET method.

Page 51: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

$_GET Examples

If the URL http://www.example.com/index.html?cat=apache&id=157

was requestedYou could access$_GET['cat'] = "apache"$_GET['id'] = "157"

Page 52: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

$_POST

• Contains information pertinent to any parameters passed using the POST method.

Page 53: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

$_POST Examples (1)<form action="subscribe.php" method="post"><p>Email address:<br /><input type="text" name="email" size="20" maxlength="50" value="" /></p><p>Password:<br /><input type="password" name="pswd" size="20" maxlength="15" value="" /></p><p><input type="submit" name="subscribe" value="subscribe!" /></p></form>

Page 54: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

$_POST Examples (2)

The following POST variables will be made available via the target subscribe.php script:

$_POST['email'] = "[email protected]";$_POST['pswd'] = "rainyday";$_POST['subscribe'] = "subscribe!";

Page 55: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

$_COOKIE

• Stores information passed into the script through HTTP cookies.

Page 56: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

$_FILES

• Contains information regarding data uploaded to the server via the POST method.

Page 57: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

$_ENV

• Offers information regarding the PHP parser’s underlying server environment.

Page 58: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Constants• boolean define (string name, mixed value [, bool case_insensitive])

define("PI", 3.141592, case_insensitive);print "The value of pi is ".PI.".<br />";$pi2 = 2 * PI;print "Pi doubled equals $pi2.";

• Note– Constant references are not prefaced with a dollar sign. – You can’t redefine or undefine the constant once it has been defined.– Constants are global.

Page 59: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

$GLOBALS

• Contains a comprehensive listing of all variables found in the global scope.

• Can be thought of as the superglobal superset.

Page 60: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

$_SESSION

• Contains information regarding all session variables.

Page 61: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

$_REQUEST

• Records variables passed to a script via any input method, specifically GET, POST, and Cookie.

Page 62: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Expressions

$a = 5; // assign integer value 5 to the variable $a$a = "5"; // assign string value "5" to the variable $a$sum = 50 + $some_int; // assign sum of 50 + $some_int to

$sum$wine = "Zinfandel"; // assign "Zinfandel" to the variable $wine$inventory++; // increment the variable $inventory by 1

Page 63: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Assignment Operators

$a = 5 Assignment $a equals 5

$a += 5 Addition-assignment $a equals $a plus 5

$a *= 5 Multiplication-assignment $a equals $a multiplied by 5

$a /= 5 Division-assignment $a equals $a divided by 5

$a .= 5 Concatenation-assignment $a equals $a concatenated with 5

Page 64: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

String Operators

$a = "abc"."def"; Concatenation $a is assigned the string “abcdef”

$a .= "ghijkl"; Concatenation-assignment $a equals its current

value concatenated with “ghijkl”

Page 65: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Increment/Decrement Operators

• ++$a, $a++ Increment Increment $a by 1• --$a, $a-- Decrement Decrement $a by 1

$inv = 15; /* Assign integer value 15 to $inv. */

$oldInv = $inv--; /* Assign $oldInv the value of $inv, then decrement $inv.*/

$origInv = ++$inv; /*Increment $inv, then assign the new $inv value to $origInv.*/

Page 66: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Logical Operators

• $a && $b And • $a AND $b And• $a || $b Or• $a OR $b Or• !$a Not• NOT $a Not• $a XOR $b Exclusive Or

Page 67: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Equality Operators

$a == $b Is equal to True if $a and $b are equivalent

$a != $bIs not equal to True if $a is not equal to $b

$a === $b Is identical to True if $a and $b are equivalent, and

$a and $b have the same type

Page 68: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Comparison Operators

$a < $b Less than $a > $b Greater than $a <= $b Less than or equal to $a >= $b Greater than or equal to

($a == 12) ? 5 : -1 Ternary If $a equals 12, return value is 5;otherwise, return value is –1

Page 69: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Bitwise Operators

• Skip for now.

Page 70: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

String Interpolation

• Strings most commonly enclosed in double quotes.

• The backslash “\” is the escape character.• Escape sequences – are ignored by the browser window.– appear in the source.

Page 71: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Recognized Escape Sequences

\n Newline character\r Carriage return\t Horizontal tab\\ Backslash\$ Dollar sign\" Double quote\[0-7]{1,3} Octal notation\x[0-9A-Fa-f]{1,2} Hexadecimal notation

Page 72: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Single Quotes

• Enclose string within single quotes when the string should be interpreted exactly as stated.

echo 'This string will $print exactly as it\'s \n declared.';

producesThis string will $print exactly as it's \n declared.

Page 73: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Heredoc

• Heredoc syntax offers a convenient means for outputting large amounts of text. Rather than delimiting strings with double or single quotes, two identical identifiers are employed.

Page 74: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Heredoc Example

<?php$website = "http://www.romatermini.it";echo <<<EXCERPT<p>Rome's central train station, known as <a href = "$website">Roma

Termini</a>,was built in 1867. Because it had fallen into severe disrepair in the

late 20thcentury, the government knew that considerable resources were

required torehabilitate the station prior to the 50-year <i>Giubileo</i>.</p>EXCERPT;?>

Page 75: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Heredoc Notes• The opening and closing identifiers must be identical.• The opening identifier must be preceded with three left-angle brackets, <<<.• Heredoc syntax follows the same parsing rules as strings enclosed in double quotes.• That is, both variables and escape sequences are parsed. The only difference is that• double quotes do not need to be escaped.• The closing identifier must begin at the very beginning of a line. It cannot be

preceded• with spaces, or any other extraneous character. This is a commonly recurring point

of• confusion among users, so take special care to make sure your heredoc string

conforms• to this annoying requirement. Furthermore, the presence of any spaces following

the• opening or closing identifier will produce a syntax error.

Page 76: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

if

<?php$secretNumber = 453;if ($_POST['guess'] == $secretNumber)

echo"<p>Congratulations!</p>";?>

Page 77: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

if-else

<?php$secretNumber = 453;if ($_POST['guess'] == $secretNumber) {echo "<p>Congratulations!!</p>";} else {echo "<p>Sorry!</p>";}?>

Page 78: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

elseif

<?php$secretNumber = 453;$_POST['guess'] = 442;if ($_POST['guess'] == $secretNumber) {echo "<p>Congratulations!</p>";} elseif (abs ($_POST['guess'] - $secretNumber) < 10) {echo "<p>You're getting close!</p>";} else {echo "<p>Sorry!</p>";}?>

Page 79: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

switch<?phpswitch($category) {case "news":print "<p>What's happening around the World</p>";break;case "weather":print "<p>Your weekly forecast</p>";break;case "sports":print "<p>Latest sports highlights</p>";break;default:print "<p>Welcome to my Web site</p>";}?>

Page 80: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

while

<?php$count = 1;while ($count < 5) {echo "$count squared = ".pow($count,2).

"<br />";$count++;}?>

Page 81: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

do while

<?php$count = 11;do {echo "$count squared = ".pow($count,2).

"<br />";} while ($count < 10);?>

Page 82: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

for

// Example Onefor ($kilometers = 1; $kilometers <= 5;

$kilometers++) {echo "$kilometers kilometers = ".

$kilometers*0.62140. " miles. <br />";}

Page 83: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

phpinfo.php

<? phpinfo(); ?>

Page 84: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Function - Definitionfunction function_name (parameters) {function-body}

function generate_footer() {echo "<p>Copyright &copy; 2006 W. Jason Gilmore</p>";}

Once it is defined, you can then call this function as you would any other. For example:

<?phpgenerate_footer();?>

Page 85: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Function - Pass by Value

function salestax($price,$tax) {$total = $price + ($price * $tax);echo "Total cost: $total";}

$total and any changes made to the parameters $price and $tax are only available inside the function.

Page 86: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Function - Pass by Reference<?php$cost = 20.00;$tax = 0.05;function calculate_cost(&$cost, $tax){// Modify the $cost variable$cost = $cost + ($cost * $tax);// Perform some random change to the $tax variable.$tax += 4;}calculate_cost($cost,$tax);echo "Tax is: ". $tax*100."<br />";echo "Cost is: $". $cost."<br />";?>

Prefixing variable name with ampersand makes it pass by reference.

Page 87: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Function - Default Argument Values

function salestax($price,$tax=.0575) {$total = $price + ($price * $tax);echo "Total cost: $total";}

$price = 19.95;$tax = .0800;salestax($price); // uses default tax of .0575salestax($price, $tax); // uses tax of .0800

Page 88: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Function - Optional Argument

function salestax($price,$tax="") {$total = $price + ($price * $tax);echo "Total cost: $total";}

Optional arguments are placed at the end of the list and assigned a default value of nothing.

salestax(42.00);

Page 89: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Function - Optional Arguments

function calculate($price,$price2="",$price3="") {

echo $price + $price2 + $price3;}

calculate(10,"",3);

Page 90: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Function – Return Valuefunction salestax($price,$tax=.0575) {$total = $price + ($price * $tax);return $total;}

function salestax($price,$tax=.0575) {return $price + ($price * $tax);}

<?php$price = 6.50;$total = salestax($price);?>

Page 91: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Function – Return Multiple Values

<?phpfunction retrieve_user_profile() {$user[] = "Jason";$user[] = "[email protected]";$user[] = "English";return $user;}

list($name,$email,$language) = retrieve_user_profile();echo "Name: $name, email: $email, preferred language: $language";?>

Page 92: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Function – Recursionfunction amortizationTable($paymentNum, $periodicPayment, $balance, $monthlyInterest) {$paymentInterest = round($balance * $monthlyInterest,2);$paymentPrincipal = round($periodicPayment - $paymentInterest,2);$newBalance = round($balance - $paymentPrincipal,2);print "<tr><td>$paymentNum</td><td>\$".number_format($balance,2)."</td><td>\$".number_format($periodicPayment,2)."</td><td>\$".number_format($paymentInterest,2)."</td><td>\$".number_format($paymentPrincipal,2)."</td></tr>";# If balance not yet zero, recursively call amortizationTable()if ($newBalance > 0) {$paymentNum++;amortizationTable($paymentNum, $periodicPayment, $newBalance, $monthlyInterest);} else {exit;}} #end amortizationTable()

Page 93: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

<?php# Loan balance$balance = 200000.00;# Loan interest rate$interestRate = .0575;# Monthly interest rate$monthlyInterest = .0575 / 12;# Term length of the loan, in years.$termLength = 30;# Number of payments per year.$paymentsPerYear = 12;# Payment iteration$paymentNumber = 1;# Perform preliminary calculations$totalPayments = $termLength * $paymentsPerYear;$intCalc = 1 + $interestRate / $paymentsPerYear;$periodicPayment = $balance * pow($intCalc,$totalPayments) * ($intCalc - 1) / (pow($intCalc,$totalPayments) - 1);$periodicPayment = round($periodicPayment,2);# Create tableecho "<table width='50%' align='center' border='1'>";print "<tr><th>Payment Number</th><th>Balance</th><th>Payment</th><th>Interest</th><th>Principal</th></tr>";# Call recursive functionamortizationTable($paymentNumber, $periodicPayment, $balance, $monthlyInterest);# Close tableprint "</table>";?>

Page 94: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Function - Libraries<?phpfunction local_tax($grossIncome, $taxRate) {// function body here}function state_tax($grossIncome, $taxRate) {// function body here}?>

Save above in file named taxation.library.php

<?phprequire_once("taxation.library.php");...?>

Page 95: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

include()• include (/path/to/filename)

• The include() statement will evaluate and include a file into the location where it is called.

• Including a file produces the same result as copying the data from the file specified into the location in which the statement appears.

• You can also execute include() statements conditionally. For example, if an include() statement is placed in an if statement, the file will be included only if the if statement in which it is enclosed evaluates to true. The include() in a conditional must be enclosed in statement block curly brackets.

Page 96: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

include_once()

• include_once (path/to/filename)

• Like include() excepts it first verifies whether or not the file has already been included. If it has already been included then include_once will not execute.

Page 97: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

require()

• Require (path/to/filename)

• works like include() except– File is include in script regardless of where

require() is located– If placed in an if statement that is false the file is

still included.– Script execution will stop if a require() fails.

Page 98: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

require_once()

• Require_once (path/to/filename)

• Like require() excepts it first verifies whether or not the file has already been included. If it has already been included then require _once will not execute.

Page 99: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Arrays

$states = array (0 => "Alabama", "1" => "Alaska"..."49" => "Wyoming");

$states[0]

$states = array ("OH" => "Ohio", "PA" => "Pennsylvania", "NY" => "New York");

$states["OH"]

Page 100: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Array - Multidimensional

$states = array ("Ohio" => array ("population" => "11,353,140",

"capital" => "Columbus"),"Nebraska" => array("population" =>

"1,711,263", "capital" => "Omaha"))

$states["Ohio"]["population"]

Page 101: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

range()

array range(int low, int high [,int step])

$die = range(0,6);// $die = array(0,1,2,3,4,5,6)

$even = range(0,20,2);// $even = array(0,2,4,6,8,10,12,14,16,18,20);

$letters = range("A","F");// $letters = array("A,","B","C","D","E","F");

Page 102: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

print_r()

Boolean print_r(mixed variable [, boolean return])

print_r($states);//sends output to standard outArray ( [Ohio] => Columbus [Iowa] => Des Moines [Arizona] => Phoenix )

// setting return to true returns output to caller.

$stateCaptials = print_r($states, TRUE);

Page 103: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Testing for an Array

• boolean is_array(mixed variable)

Page 104: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

Adding array elements

$states["Ohio"] = "March 1, 1803“

$state[] = "Ohio";If index is numerical you can append an element

by leaving the index blank

Page 105: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

array_push()int array_push(array target_array, mixed variable [, mixed variable...])

$states = array("Ohio","New York");

array_push($states,"California","Texas");

// $states = array("Ohio","New York","California","Texas");

Appends to end of array.Returns TRUE on success.

Page 106: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

array_pop()

mixed array_pop(array target_array)

$states = array("Ohio","New York","California","Texas");

$state = array_pop($states); // $state = "Texas“

Returns last element from target_array, resetting array pointer upon completion.

Page 107: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

array_shift()

mixed array_shift(array target_array)$states = array("Ohio","New York","California","Texas");$state = array_shift($states);// $states = array("New York","California","Texas")// $state = "Ohio"

Returns first element from target_array, resetting array pointer upon completion.

If numerical keys are used, all corresponding values will be shifted down, whereas arrays using associative keys will not be affected.

Page 108: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

array_unshift()int array_unshift(array target_array, mixed variable [, mixed variable...])$states = array("Ohio","New York");array_unshift($states,"California","Texas");// $states = array("California","Texas","Ohio","New York");

Adds elements to the front of the array rather than to the end.

All preexisting numerical keys are modified to reflect their new position in the array, but associative keys aren’t affected.

Page 109: PHP Basics Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional

array_pad()array array_pad(array target, integer length, mixed pad_value)$states = array("Alaska","Hawaii");$states = array_pad($states,4,"New colony?");$states = array("Alaska","Hawaii","New colony?","New colony?");

Increases array size to the length specified by length. This is done by padding the array with the value specified by pad_value. If pad_value is positive, the array will be padded to the right side (the end); if it is negative, the array will be padded to the left (the beginning). If length is equal to or less than the current target size, no action will be taken.