PHP I : Resources

Resources

Operators

 

PHP5 Power Programming – Free Book Download at
http://www.computer-books.us/php_2.php

 

Beginner PHP Tutorials at
http://www.justphukit.com/php/beginner-php-tutorials.php

Learning PHP: Installing and Configuring By Elizabeth Fulghum at
http://www.developer.com/lang/article.php/912381

An Introduction to PEAR by Joao Prado Maia at
http://www.onlamp.com/pub/a/php/2001/05/24/pear.html

A Detailed Look at PEAR by Joao Prado Maia
http://www.onlamp.com/pub/a/php/2001/07/19/pear.html

PHPKitchen.com’s PEAR Tutorials at
http://www.phpkitchen.com/index.php?/archives/668-PEAR-Tutorials.html

 

See the University of Washington’s “Using a php.ini file” at
http://www.washington.edu/computing/web/publishing/php-ini.html

…as well as the PHPFreaks.com “PHP.INI Setup!!” article at
http://www.phpfreaks.com/tutorials/72/0.php

 

PHP I : Regular Expressions

Regular Expressions

Follow this lesson in Ullman Chapter 13. The scripts are located in the 13 directory.

If you aren’t familiar with using them see my Shell Scripting section on Regular Expressions.

Have you used grep? If you have you’re going to recognize this syntax. If you haven’t, see my Linux Fundamentals section on grep.

However, WATCH OUT if you’re a grep user! Some of the characters are different here!

 

Pattern Matching Using Regular Expressions (regex)

Use it like this:

$pattern = “Flintstones”;
$string = “Flintstones! Meet the Flintstones!”;
ereg ($pattern, $string);

This makes a lot more sense when you think in terms of trying to find which member of an array matches a pattern, or which line of a file matches the pattern.

 

PHP’s POSIX Extended Functions
ereg() Match a pattern in a string ereg (‘pattern‘, ‘string‘);
eregi() Same, case-insensitive eregi (‘pattern‘, ‘string‘);
ereg_replace() Match and replace a pattern in a string ereg_replace ( ‘pattern‘, ‘replacement‘, ‘string‘ )
eregi_replace() Same, case-insensitive eregi_replace ( ‘pattern‘, ‘replacement‘, ‘string‘ )
split() Split a string into an array, splitting at pattern, up to an optional limit of times.

split ( ‘pattern‘, ‘string‘ [, limit] )

spliti() Same, case-insensitive spliti( ‘pattern‘, ‘string‘ [, limit] )
preg_match() Similar, using regular expression matching preg_match (‘pattern‘, ‘string‘);

 

Literals

Literals match literally themselves:

ereg (‘Flintstones’, ‘Meet the Flintstones’);

will return TRUE.

You can specify lists of literals:

 

Metacharacters and Quantifiers

.
Matches a single character.
*
Matches zero or more instances of the immediately preceding character. Example: C* if found would match C, CC or CCC … not to mention a blank string!
?
Matches one or more instances of the immediately preceding character. Example: C? if found would match C, CC or CCC …
( )
Group
|
“Or” – (mouse|cat|dog)
^
Represents the beginning of the string, so if you specified ^T grep would search for any string starting with a T.
$
Represents the end of the string, so if you specified \.$ then grep would pull up any string that ended with .
\
The escape character: it means to take the next character literally, so you can search for characters like * that have special meanings: \*
{x}
Exactly x occurrences of the preceding character or expression
{x, y}
Between x and y occurrences of the preceding character or expression
{x,}
At least x occurrences of the preceding character or expression

 

Character Classes

This is simply a term for grouping options in square brackets. For instance:

[HhJ]ello matches lines containing hello or Hello or Jello.

 

Use the ^ character before a character or expression to indicate negation:
^a is “NOT a”.

The $ character and the . character are NOT wildcards inside character classes (inside [ ] characters).

Ranges of characters are also permitted:

[0-3] is the same as [0123]
[a-k] is the same as [abcdefghijk]
[A-C] is the same as [ABC]
[A-Ca-k] is the same as[ABCabcdefghijk]
[ \f\r\t\n\v] matches any white space

 

There are also some alternate forms :

[[:alpha:]] is the same as [a-zA-Z]
[[:upper:]] is the same as [A-Z]
[[:lower:]] is the same as [a-z]
[[:digit:]] is the same as [0-9]
[[:alnum:]] is the same as [0-9a-zA-Z]
[[:space:]] matches any white space

 

 

Matching and Replacing Patterns

Do it like this:

$pattern = “Flintstones”;
$replacement = “Jetsons”;
$string = “Flintstones! Meet the Flintstones!”;
eregi_replace ($pattern, $replacement, $string);

 

 

 

To do out of class:

Review Chapter 13 of Ullman.

PHP I : Database Connections

Follow this lesson in Ullman Chapter 12. The scripts are located in the 12 directory.

For this discussion, you will need to create a testing file. I suggest you call it test.php and save it in your local web root.

As we discuss each code block, you can paste it into test.php and view it (run it) in your browser.

 

Connecting to MySQL

$dbc = mysql_connect (‘hostname’, ‘username’, ‘password’)

Set Up These Values In An Included File That Is Outside Your Web Root!

The dbcon.php file:

<?php
$server = ‘localhost’; // DATABASE SERVER
$database = ‘myblog’; // DATABASE NAME
$user = ‘root’; // USER NAME
$password = ”; // USER PASSWORD
?>

Specifying dbcon.php as an include in your PHP code:

<?
include (‘../../../dbcon.php’);
….
?>

See the script mysql_connect.php in the 12 directory.

 

MySQL Error Handling

mysql_err()

die()

 

// Attempt to connect to MySQL and print out messages.
if ($dbc = mysql_connect (‘localhost’, ‘root’, ”)) {

print ‘<p>Successfully connected to MySQL.</p>’;

mysql_close(); // Close the connection.

} else {

print ‘<p>Could not connect to MySQL.</p>’;

 

// Attempt to connect to MySQL and print out messages.
if ($dbc = @mysql_connect (‘localhost’, ‘root’, ”)) {

print ‘<p>Successfully connected to MySQL.</p>’;

mysql_close(); // Close the connection.

} else {

die (‘<p>Could not connect to MySQL because: <b>’ . mysql_error() . ‘</b></p>’);

}

Note the use of “@” and mysql_error().

 

Creating a Database

Note that you have to connect to the MySQL server before you can create a database within it.

if (@mysql_query (‘CREATE DATABASE myblog’)) {
print ‘<p>The database has been created.</p>’;
} else {
die (‘<p>Could not create the database because: <b>’ . mysql_error() . ‘</b></p>’);
}

 

Selecting a Database

Note that you have to connect to the MySQL server before you can select a database within it.

//Attempt to select a database, after connecting
if (@mysql_select_db (‘myblog’)) {
print ‘<p>The database has been selected.</p>’;
} else {
die (‘<p>Could not select the database because: <b>’ . mysql_error() . ‘</b></p>’);
}

 

Creating a Table

Note that you have to connect to the MySQL server and select a database before you can create or access tables.

// Define the query.
$query = ‘CREATE TABLE blog_entries (
blog_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100) NOT NULL,
entry TEXT NOT NULL,
date_entered DATETIME NOT NULL
)’;

// Run the query.
if (@mysql_query ($query)) {
print ‘<p>The table has been created.</p>’;
} else {
die (‘<p>Could not create the table because: <b>’ . mysql_error() . ‘</b>.</p><p>The query being run was: ‘ . $query . ‘</p>’);
}

 

INSERT INTO: Adding Data

INSERT INTO tablename (column1_name, column2_name, column3_name) values (‘value1’, ‘value2’, ‘value3’)

INSERT INTO tablename values (‘value1’, ‘value2’, ‘value3’)

 

SELECT: Getting Data

Note that you have to connect to the MySQL server and select a database before you can create or access tables.

// Define the query.
$query = ‘SELECT title, entry FROM blog_entries ORDER BY date_entered DESC’;

if ($r = mysql_query ($query, $dbc)) { // Run the query.

// Retrieve and print every record.
while ($row = mysql_fetch_array ($r)) {
print “{$row[‘title’]} {$row[‘entry’]}<br />”;
}

} else { // Query didn’t run.
die (‘<p>Could create the table because: <b>’ . mysql_error() . “</b>. The query was $query.</p>”);
}

 

DELETE: Deleting Data

Note that you have to connect to the MySQL server and select a database before you can create or access tables.

// Define the query.
$query = “DELETE FROM blog_entries WHERE blog_id={$_POST[‘id’]} LIMIT 1″;
$r = mysql_query ($query); // Execute the query.

// Report on the result.
if (mysql_affected_rows() == 1) {
print ‘<p>The blog entry has been deleted.</p>’;
} else {
print “<p>Could delete the entry because: <b>” . mysql_error() . “</b>. The query was $query.</p>”;
}

 

UPDATE: Changing Existing Data

Ullman’s Update Script: (edited)

// Define the query.
$query = “UPDATE blog_entries SET title='{$_POST[‘title’]}’, entry='{$_POST[‘entry’]}’ WHERE blog_id={$_POST[‘id’]}”;
$r = mysql_query ($query); // Execute the query.

// Report on the result.
if (mysql_affected_rows() == 1) {
print ‘<p>The blog entry has been updated.</p>’;
} else {
print “<p>Could update the entry because: <b>” . mysql_error() . “</b>. The query was $query.</p>”;
}

 

Close Your Database Connection!

ALWAYS close your database connection at the end of your script!

mysql_close()

That’s all it takes.

 

To do out of class:

Review Chapter 12 of Ullman.

PHP I : Files & Directories

Follow this lesson in Ullman Chapter 11. The scripts are located in the 11 directory.

 

resource fopen ( string filename, string mode [, int use_include_path [, resource zcontext]])

 

OS File Permissions

See my Linux Fundamentals page on Permissions for a discussion of setting and viewing permissions on Linux/Unix computers.

 

File Permissions Settings in PHP

Use phpinfo() to check two things:

Is PHP running in Safe Mode?

Is the open_basedir directive set?

 

Writing to Files

Create a file pointer ($fp, or any name you choose), and use it to open, write to and close a file:

$fp = fopen(‘filename‘, ‘mode‘);
fwrite ($fp, ‘data to write‘);
fclose ($fp);

 

r
Open for reading only.
Place the file pointer at the beginning of the file.
r+
Open for reading and writing.
Place the file pointer at the beginning of the file.
w
Open for writing only.
Place the file pointer at the beginning of the file.
Truncate the file to zero length.
If the file does not exist, attempt to create it.
w+
Open for reading and writing.
Place the file pointer at the beginning of the file.
Truncate the file to zero length.
If the file does not exist, attempt to create it.
a
Open for writing only.
Place the file pointer at the end of the file.
If the file does not exist, attempt to create it.
a+
Open for reading and writing.
Place the file pointer at the end of the file.
If the file does not exist, attempt to create it.
x
Create and open for writing only.
Place the file pointer at the beginning of the file.
If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING.
If the file does not exist, attempt to create it.
x+
Create and open for reading and writing.
Place the file pointer at the beginning of the file.
If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING.
If the file does not exist, attempt to create it.
t
Add to any of the above.
Use in Windows only to “fix” line endings.
b
Add to any of the above (except t).
Use to force binary mode, i.e. ignore line ending differences.

 

Unix based systems use \n as the line ending character.

Windows based systems use \r\n as the line ending.

In Windows, use the text-mode translation flag (‘t’) to transparently translate \n to \r\n.

In either platform, use ‘b’ to force binary mode, which will not change your file.

To use these flags, specify either ‘b’ or ‘t’ as the last character of the mode parameter.

 

Also see file_put_contents() at
http://us2.php.net/manual/en/function.file-put-contents.php

 

Checking For Writeability

if (is_writeable(‘../somefile‘)) {
 //perform a file open here
} else {
 print “File is not writeable.”;
}

 

Locking Files

//Open the file first, then to write
//to it, use this:
flock ($fp, LOCK_EX);
// Write the data. Use \r\n on Windows.
fwrite ($fp, “$data\n”);
flock ($fp, LOCK_UN);
// Close the file.
fclose ($fp);

flock() doesn’t work on NTFS or FAT file systems.

 

Reading from Files

//This gets the file contents as an indexed array:
$my_data = file (‘../somefile‘);

//This gets the file contents as a single string:
$my_data = file_get_contents (‘../somefile‘);

 

Uploading Files

1. In the <form> tag, you must add the code:

enctype=”multipart/form-data”

so the browser knows you may ask it to pass a file.

2. You must add the hidden input:

<input type=”hidden” name=”MAX_FILE_SIZE” value=”3000″ />

3. You just add a form input:

<input type=”file” name=”my_file” />

You can use any element name you want instead of my_file; just remember to use that name consistently to access the data later.

Upon submission, the file is passed from the browser to the server in the $_FILES array, which has five elements:

name – the name of the file on the sender’s computer

type – MIME type

size – in bytes

tmp_name – the download temporary file name on the server

error – the error code

Then, you capture the temporary upload file and move it to its intended destination:

move_uploaded_file($_FILES[‘my_file‘][‘tmp_name’], ‘destination/folder/filename‘);

This is best done with error-checking:

// The acid test: can we move the uploaded file?
if (move_uploaded_file ($_FILES[‘my_file’][‘tmp_name’], “../uploads/{$_FILES[‘my_file’][‘name’]}”)) {

print ‘<p>Your file has been uploaded.</p>’;

} else { // We have a problem!

Definitely see Ullman page 319 for a complete example!

 

Also see unlink() to delete files, and copy() to move/copy files.

 

Navigation and Directory Listing: PHP 4

// Specify a directory name
$directory = ‘.’;

//Open the directory
$dp = opendir ($directory);

// List the directories first.
while ($item = readdir ($dp)) {
if((is_dir($item)) AND (substr($item,0,1) != ‘.’)){
print “$item\n”;
}
}

// Reset the pointer
rewinddir ($dp);

// List the files.
while ($item = readdir($dp)) {
if ( (is_file($item)) AND (substr ($item,0,1) != ‘.’)) {

// Get the file size.
$fs = filesize ($item);

// Get the file’s modification date.
$lm = date (‘F j, Y’, filemtime ($item));

// Print the information.
print “$item\n $fs bytes\n $lm\n”;

} // Close the if
} // Close the while

// Close the directory
closedir ($dp);

See Ullman pp. 324 ff. for an example including table formatting. It’s quite good.

 

Navigation and Directory Listing: PHP 5

// Specify a directory name
$directory = ‘.’;

$files = scandir($directory);

// List the directories first.
foreach ($files as $item) {
if((is_dir($item)) AND (substr($item,0,1) != ‘.’)){
print “$item\n”;
}
}

// Reset the pointer
rewinddir ($dp);

// List the files.
foreach ($files as $item) {
if ( (is_file($item)) AND (substr ($item,0,1) != ‘.’)) {

// Get the file size.
// Note the human_readable function!
$fs = human_readable (filesize ($item));

// Get the file’s modification date.
$lm = date (‘F j, Y’, filemtime ($item));

// Print the information.
print “$item\n $fs bytes\n $lm\n”;
}
}

See also fileperms(), fileatime() and fileowner().

 

Creating Directories

mkdir(‘directory_name‘, permissions);

mkdir(‘mysecrets’, 0777);

 

Reading Files Incrementally

// Open the file.
$fp = fopen (‘../user/passwords.txt’, ‘rb’);

// Loop through the file.
while ( $line = fgetcsv ($fp, 100, “\t”)) {

// Do something to each line, such as a test
if ( ($line[0] == $_POST[‘username’]) AND ($line[1] == crypt ($_POST[‘password’], $line[1]) ) ) {

// In this case, we’ve found a
// correct username/password combination.
$loggedin = TRUE;

// Stop looping through the file.
break;

} // End if

} // End while

fclose ($fp); // Close the file

 

To do out of class:

Review Chapter 11 of Ullman.

PHP I : Functions

PHP Function Refence:
http://www.php.net/manual/en/funcref.php

Follow this lesson in Ullman Chapter 10. The scripts are located in the 10 directory.

 

Creating and Calling a User-Defined Function

function function_name () {
  #do stuff here
}

Function names are case-insensitive!

For example:

<?php
function my_first_function() {
for($i = 0; $i < 10; $i++) {
  echo “This is iteration $i. <br />”;
}
}

echo “Here’s where we call my_first_function: <br />”;
my_first_function();
echo “The function has completed.”;
?>

 

Checking That a Function Exists

if (function_exists(‘my_first_function’)) {
….
}

 

Using Arguments

function function_name (argument1, argument2, …) {
  #do stuff here
}

For example:

<?php
function my_arguments_function($user_name, $user_title) {
echo “Hi, $user_name.<br />”;
echo “You are a(n) $user_title.<br />”;
}

echo “Here’s where we call my_arguments_function: <br />”;
my_arguments_function(‘Fred’, ‘Antihero’);
echo “The function has completed.”;
?>

 

Default Argument Values

<?php
// Notice that if no message is passed,
// “Hi there” is used by default:

function my_defaults_function ($count, $msg = “Hi there.”) {
for($i = 0; $i < $count; $i++){
  echo “Saying: $msg for repetition: $i .”<br />”;
}
}
echo “Print it 3 times ….<br />”;
my_defaults_function (3, “Hello”);
?>

Default argument values, if there are any, must be named last! This has the benefit of making them optional.

 

Return Values

Use the return statement:

function function_name ($arg1) {
  statements();
  return $value
;
}

For instance:

function my_calculator ($quantity, $price) {

// Calculate:
$total = $quantity * $price;
// Format:
$total = number_format ($total, 2);

// Return the value:
return $total;

}

Then use it like this:

$sale_total = my_calculator ($order_qty, $sale_price);

 

Variable Scope

A variable you declare within a function is local to that function. It isn’t available elsewhere.

Variables declared using global are exactly that: available globally, both within and outside of particular functions.

Environment variables (like $_SERVER[‘PHP_SELF’]) are available not just to your PHP environment, but to everyone’s.

To use a global variable, declare it early in your script, outside any function:

$tax_rate = 6.875;

Then you can make this declaration within a function:

global $tax_rate;

Your script will use the external (global) variable, as long as it exists outside the function.

 

To do out of class:

Review Chapter 10 of Ullman.

PHP I : Cookies & Sessions

Follow this lesson in Ullman Chapter 9. The scripts are located in the 09 directory.

 

Creating Cookies

setcookie (‘cookie_name‘, ‘cookie_value‘);

or more formally:

bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure [, bool httponly]]]]]] )

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script. Do this by using output buffering.

 

Buffering header output for cookies

This must go ABOVE all other code, before the HTML declarations, before EVERYTHING:

<?php
ob_start();
// This starts output buffering
?>

Then this must go BELOW all other code, after closing body and HTML declarations, after EVERYTHING:

<?php
ob_end_flush (); // Sends the page
?>

 

Cookie values

A cookie can be as simple as:

setcookie(‘mycookie’,’value’);

or as complete as:

setcookie(‘username’, ‘Fred’, time()+60*60*24*30, ‘/’, ‘.somedomain.com’, 1, 1);

For example:

<?php
// Set cookies

$visit=$visits + 1;
$exp=time()+365*24*60*60;
setcookie(“visits”, “$visit”,$exp);
echo “You have visited “.$_COOKIE[“visits”].” times”;
?>

 

Reading Cookies

$_COOKIE

If you performed:

setcookie (‘user’, ‘user_name‘);

Then you could retrieve:

print $_COOKIE[‘user’];

Or:

if (isset($_COOKIE[‘user’])) {
  print $_COOKIE[‘user’];
}

When you set a cookie, it’s not available until the next page load occurs.

 

Cookie Parameters

setcookie ( ‘name‘, ‘value‘, ‘expiration‘, ‘path‘, ‘domain‘, ‘secure‘, ‘http_only‘)’

name – the cookie’s name; you may be setting more than one

expiration – (seconds since the epoch) – use time()+number_of_seconds, for instance:

$expire = time() + 60 * 60 * 24 * 30

path – limit to a specific folder on a web site

domain – limit to a specific domain

secure – limit to https connections (1) or not (0)

http_only – make cookie available for call only from http documents, not from JavaScript or PHP, for instance.

 

Deleting Cookies

If you:

setcookie (‘user’, ‘Fred’);

Then:

setcookie (‘user’, ”);

Or even more:

setcookie (‘user’, ‘Fred’, time() – 60);

 

To do out of class:

Review Chapter 9 of Ullman.

PHP I : Web Apps

Follow this lesson in Ullman Chapter 8. The scripts are located in the 08 directory.

 

Checking for Form Submission

if (isset ($_POST[‘submit’])) {
//Handle the form
….
}

 

Using include() and require()

See Ullman page 198.

<?php
include (‘../../../dbcon.php’);
….
?>

Included files are “brought in” to the current file. If include() fails, PHP simply generates a warning (which is visible to visitors on the web).

<?php
require (‘../../../dbcon.php’);
….
?>

Required files are also “brought in” to the current file. But if require() fails, PHP stops execution of the script.

See also include_once() and require_once().

 

Constants

You can’t change it after you set it!

define (‘CONSTANT’, ‘value);

for instance:

define (‘PI’, 3.1416);

Constants DO NOT USE THE $:

print PI;

Constants WON’T PRINT WITHIN ANY QUOTATION MARKS. Use concatenation to print them:

print ‘Pi equals ‘ . PI;

 

defined(‘PI’) //returns TRUE
defined(‘foo’) //returns FALSE

See Ullman page 207 for this usage.

 

PHP_VERSION

PHP_OS

 

Date and Time

date(‘format’)

See Ullman page 209 for format options

time()

mktime()

 

Self-Referral: Presenting a Form and Handling Submission In a Single Page

if(isset($_POST[‘submit’])) {
   //Then handle the form
} else {
   //Display the form here
}

 

Making Forms Sticky

See Ullman’s register.php script for the full text.

// Display the form.
print ‘<form action=”register.php” method=”post”><p>’;

print ‘Username: <input type=”text” name=”username” size=”20″ value=”‘ . $_POST[‘username’] . ‘” /><br />’;

 

Sending email with PHP

mail ( ’email_address’, ‘subject’, ‘message’);

Life will be much easier if you populate a variable with the message, and use that variable as the third parameter.

 

Output Buffering

This function simply sends the output of your page/script to a buffer, so that time-sensitive functions like session_start() won’t run until ready.

Place this at the very top of your code, before everything, including <html> and <head> elements:

<?php
ob_start();
?>

Place this at the very end of your code, after everything, including the </body> and </html> elements:

<?php
ob_end_flush();
?>

<?php
ob_end_clean();
?>

Either of these last two turn off buffering.

See Ullman page 231 for other buffer functions.

 

HTTP Headers

Header functions must be called before anything else is sent to the browser!

The most frequent use is for redirecting the user to a new page:

header(‘Location: some_page.php);
exit();

 

To do out of class:

Review Chapter 8 of Ullman.

PHP I : Arrays

Follow this lesson in Ullman Chapter 7. The scripts are located in the 07 directory.

 

The arrays you’re already using: $_GET and $_POST

These two arrays are two of the superglobals.

Older versions of PHP (before 4.1) use $HTTP_POST_VARS and $HTTP_GET_VARS instead.

Other superglobals include $_COOKIE, $_SESSION AND $_SERVER.

 

An Indexed Array
0 Fred
1 Barney
2 Wilma
3 Betty

 

A Keyed Array
hero Fred
hero_buddy Barney
hero_wife Wilma
buddy_wife Betty

 

Creating an Array

$flintstones = array(‘Fred’, ‘Barney’, ‘Wilma’, ‘Betty’);

$flintstones = array(1 => ‘Fred’, 2 => ‘Barney’, 3 => ‘Wilma’, 4 => ‘Betty’);

or

$flintstones = array(
1 => ‘Fred’,
2 => ‘Barney’,
3 => ‘Wilma’,
4 => ‘Betty’
);

or even

$flintstones = array(
1 => ‘Fred’,
‘Barney’,
‘Wilma’,
‘Betty’
);

Note that if you do not specify a starting index, your array is numbered starting with 0 !

 

$flintstones = array(‘hero’ => ‘Fred’, ‘hero_buddy’ => ‘Barney’, ‘hero_wife’ => ‘Wilma’, ‘buddy_wife’ => ‘Betty’);

or

$flintstones = array(
‘hero’ => ‘Fred’,
‘hero_buddy’ => ‘Barney’,
‘hero_wife’ => ‘Wilma’,
‘buddy_wife’ => ‘Betty’
);

 

Other Types of Arrays

Range:

$numbers = range(1, 10);

$letters = range(‘a’, ‘z’)

# You can use a third “step” parameter:

$even_numbers = range(0, 100, 2);

 

Printing an Array

You don’t always get what you expect.

print $flintstones;

gets you:

Array

While

print_r($flintstones);

gets you:

Array { [hero] => Fred [hero_buddy] => Barney [hero_wife] => Wilma [buddy_wife] => Betty }

Compare:

var_dump($flintstones);

 

Create a new PHP page with a form. The form should have at least four text boxes. It should allow the user to create an array, and it should print out that array as the result.

 

Adding to an Array

Add to an Indexed Array:

$flintstones[] = Pebbles;
$flintstones[] = Bam-Bam;
# if you specify no index, it’s added automatically

Add to a Keyed Array:

$flintstones[hero_daughter] = Pebbles;
$flintstones[buddy_son] = Bam-Bam;

 

Modifying an Array

$flintstones[6] = Boom-Boom;
# if you specify an existing index,
# the current value is modified

 

Deleting Items from an Array

unset($flintstones[6]);

or

unset($flintstones[‘buddy_son’]);

 

Clearing All Values from an Array

unset($flintstones);

or

$flintstones = array();

 

Counting the Elements of an Array

count($flintstones);

 

Accessing the Elements of an Array

print “The protagonist of The Flintstones is {$flintstones[‘hero’]}“;

or

print “The protagonist of The Flintstones is {$flintstones[‘1’]}“;

Note the all-important Curly Braces!

 

foreach ($array as $key => $value) {
   print “Key is $key. \n Value is $value.”;
}

 

foreach ($flintstones as $key => $value) {
   print “Key is $key. \n Value is $value.”;
}

 

Multidimensional Arrays: Arrays of Arrays

// Create the first array.
$veggies = array (1 => ‘lettuce’, ‘broccoli’, ‘carrots’, ‘turnips’);

// Create the second array.
$meats = array (1 => ‘beef’, ‘fish’, ‘pork’, ‘mystery’);

// Create the third array.
$dairy = array (1 => ‘milk’, ‘cream’, ‘butter’, ‘eggs’);

// Create the multidimensional array.
$food = array (
‘veg’ => $veggies,
‘meat’ => $meats,
‘dair’ => $dairy
);

 

Accessing Individual Elements of Multidimensional Arrays

$food[‘veg’][1]

print “Eat your {$food[‘veg’][1]}“;

Once again note the all-important Curly Braces!

 

Displaying All Elements of Multidimensional Arrays

foreach ($food as $food_group => $food_item) {
   print “$food_group”;

foreach ($food_item as $index => $food_name)
{
print “Item $index is $food_name”;
}

}

 

Sorting an Array

To sort alpha/numerically by the values:

sort($array)

Or reversed:

rsort($array)

Either of the above destroys the relationship between key and value! Use them only for indexed arrays.

 

To sort values while PRESERVING key/value relationships:

asort($array)

Or reversed:

arsort($array)

 

To sort keys while preserving key/value relationships:

ksort($array)

krsort($array)

 

To randomize (unsort) an array:

shuffle($array)

 

To sort using “natural order:”

natsort($array)

natcasesort($array)

 

Create variables from the values of an array:

$name = array(‘first’ => ‘Glenn’, ‘last’ => ‘Norman’);

extract($name);

print $first; # prints “Glenn”

print $last; # prints “Norman”

extract() is for Associative Arrays.

 

$date = array(‘January’, ’20’, ‘2009’);

list($month, $day, $year) = $date;

list() is for Indexed Arrays.

 

Transformation: Strings to Arrays and Back Again

Turn a string into an array (specifying the separator):

$array = explode($separator, $string);

$array = explode(‘,’, $string);

$array = explode(‘ ‘, $string);

Turn an array into a string :

$string = implode($glue, $array);

$string = implode(‘,’, $array);

$string = implode(‘ ‘, $array);

Also see the join() function, which is identical to implode().

 

A Jillion More Array Functions:

Array Functions at http://www.php.net/manual/en/ref.array.php

 

To do out of class:

Review Chapter 7 of Ullman.

PHP I : Control Structures

Follow this lesson in Ullman Chapter 6. The scripts are located in the 06 directory.

See the pages register.html and handle_reg.php described on Ullman pages 114ff.

 

Operators

PHP Operators: Tests of Equality and so forth
+
Addition Arithmetic
Subtraction Arithmetic
*
Multiplication Arithmetic
/
Division Arithmetic
%
Modulus (remainder after division) Arithmetic
++
Increment (add 1) Arithmetic
Decrement (subtract 1) Arithmetic
=
Assignment Assignment
==
Equality (for testing) Comparison
!=
Inequality Comparison
<
Less than Comparison
>
Greater than Comparison
<=
Less than or equal to Comparison
>=
Greater than or equal to Comparison
!
Negation; negates any test Logical
AND
&&
And Logical
OR
||
Or

Logical

XOR
Or NOT Logical
.
Concatenation String
.=
Concatenate to (put on the end of) the current value Concatenation and
Assignment
+=
Add to the current value Concatenation and
Arithmetic
-=
Subtract from the current value Concatenation and
Arithmetic

See the PHP.net manual page on Operators at http://us2.php.net/manual/en/language.operators.php

 

Using the if conditional

if (condition) {
#do stuff
}

or:

if (condition)
{
#do stuff
}

 

Things you can test

Is a variable empty?

empty()
# var is null, 0 or “”
# Returns TRUE or FALSE

Is a variable not null?

isset()
# var is not null
# var can be 0 or “”
# Returns TRUE or FALSE

Is a variable numeric?

is_numeric()
# var is numeric
# Returns TRUE or FALSE

Is a variable an array?

is_array()
# var is an array
# Returns TRUE or FALSE

Is a variable a string?

is_string()
# var is a string
# Returns TRUE or FALSE

Is a variable an integer?

is_integer()
# var is an array
# Returns TRUE or FALSE

Is a variable a real date?

checkdate()
# var is a truly possible date
# Returns TRUE or FALSE

 

Using if/else

if (condition) {
#do stuff
} else {
#do different stuff
}

 

Using if/elif/else

if (condition) {
  # do option a
} elif (condition) {
  # do option b
} else {
  # do some default option
}

 

Using the Switch Conditional

switch ($variable) {
  case “value1” :
    option1_code();
    break;
  case “value2” :
    option2_code();
    break;
  default :
    default_code();
    break;
}

 

The for Loop

for (starting_value, ending_value, increment) {
   # do some stuff each time
}

It may make more sense like this:

for ($x = 1, $x < 10, $x++) {
   # do some stuff each time
   print “\$x is now $x”;
}

 

The foreach Loop

foreach ($array as $key => $value) {
   print “Key is $key. \n Value is $value.”;
}

 

The while Loop

while (this_condition_is_true) {
   #do stuff
}

A while loop can’t set initial conditions and can’t execute closing expressions.

A while loop may not execute even once if the initial condition is false!

 

The do…while Loop

do {
   # stuff
} while (condition_is_true)

 

A do…while loop will always execute at least once.

 

Break!  Continue!  Exit!  and  Die!

Break: Exit the loop. Code that follows the loop executes.

Continue: Leave the current point in the loop. Loop continues to execute.

Exit: Stop executing all PHP code! – and don’t send following HTML code.

Die: Stop executing all PHP code! – and don’t send following HTML code.

 

Outside of class:

Review Chapter 6 of Ullman.