BUY THIS BOOK
Add to Cart

Print Book $44.99


Add to Cart

Print+PDF $58.49

Add to Cart

PDF $35.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £31.99

What is this?

Looking to Reprint or License this content?


PHP Cookbook
PHP Cookbook, Second Edition

By Adam Trachtenberg, David Sklar
Book Price: $44.99 USD
£31.99 GBP
PDF Price: $35.99

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Strings
Strings in PHP are sequences of bytes, such as “We hold these truths to be self-evident” or “Once upon a time” or even “111211211.” When you read data from a file or output it to a web browser, your data are represented as strings.
PHP strings are binary-safe (i.e., they can contain null bytes) and can grow and shrink on demand. Their size is limited only by the amount of memory that is available to PHP.
Usually, PHP strings are ASCII strings. You must do extra work to handle non-ASCII data like UTF-8 or other multibyte character encodings, see .
Similar in form and behavior to Perl and the Unix shell, strings can be initialized in three ways: with single quotes, with double quotes , and with the “here document” (heredoc) format. With single-quoted strings, the only special characters you need to escape inside a string are backslash and the single quote itself. shows four single-quoted strings.
Example . Single-quoted strings
print 'I have gone to the store.';
print 'I\'ve gone to the store.';
print 'Would you pay $1.75 for 8 ounces of tap water?';
print 'In double-quoted strings, newline is represented by \n';
prints:
I have gone to the store.
I've gone to the store.
Would you pay $1.75 for 8 ounces of tap water?
In double-quoted strings, newline is represented by \n
Because PHP doesn’t check for variable interpolation or almost any escape sequences in single-quoted strings, defining strings this way is straightforward and fast.
Double-quoted strings don’t recognize escaped single quotes, but they do recognize interpolated variables and the escape sequences shown in .
Table 1-1: Double-quoted string escape sequences
Escape sequence
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
Strings in PHP are sequences of bytes, such as “We hold these truths to be self-evident” or “Once upon a time” or even “111211211.” When you read data from a file or output it to a web browser, your data are represented as strings.
PHP strings are binary-safe (i.e., they can contain null bytes) and can grow and shrink on demand. Their size is limited only by the amount of memory that is available to PHP.
Usually, PHP strings are ASCII strings. You must do extra work to handle non-ASCII data like UTF-8 or other multibyte character encodings, see .
Similar in form and behavior to Perl and the Unix shell, strings can be initialized in three ways: with single quotes, with double quotes , and with the “here document” (heredoc) format. With single-quoted strings, the only special characters you need to escape inside a string are backslash and the single quote itself. shows four single-quoted strings.
Example . Single-quoted strings
print 'I have gone to the store.';
print 'I\'ve gone to the store.';
print 'Would you pay $1.75 for 8 ounces of tap water?';
print 'In double-quoted strings, newline is represented by \n';
prints:
I have gone to the store.
I've gone to the store.
Would you pay $1.75 for 8 ounces of tap water?
In double-quoted strings, newline is represented by \n
Because PHP doesn’t check for variable interpolation or almost any escape sequences in single-quoted strings, defining strings this way is straightforward and fast.
Double-quoted strings don’t recognize escaped single quotes, but they do recognize interpolated variables and the escape sequences shown in .
Table 1-1: Double-quoted string escape sequences
Escape sequence
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Accessing Substrings
You want to know if a string contains a particular substring. For example, you want to find out if an email address contains a @.
Use strpos(  ) , as in .
Example . Finding a substring with strpos(  )
<?php

if (strpos($_POST['email'], '@') === false) {
    print 'There was no @ in the e-mail address!';
 }

?>
The return value from strpos(  ) is the first position in the string (the “haystack”) at which the substring (the “needle”) was found. If the needle wasn’t found at all in the haystack, strpos(  ) returns false. If the needle is at the beginning of the haystack, strpos(  ) returns 0, since position 0 represents the beginning of the string. To differentiate between return values of 0 and false, you must use the identity operator (===) or the not–identity operator (!==) instead of regular equals (==) or not-equals (!=). compares the return value from strpos(  ) to false using ===. This test only succeeds if strpos returns false, not if it returns 0 or any other number.
Documentation on strpos(  ) at http://www.php.net/strpos.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Extracting Substrings
You want to extract part of a string, starting at a particular place in the string. For example, you want the first eight characters of a username entered into a form.
Use substr(  ) to select your substring, as in .
Example . Extracting a substring with substr(  )
<?php
$substring = substr($string,$start,$length);
$username = substr($_GET['username'],0,8);
?>
If $start and $length are positive, substr(  ) returns $length characters in the string, starting at $start. The first character in the string is at position 0. has positive $start and $length.
Example . Using substr(  ) with positive $start and $length
print substr('watch out for that tree',6,5);
prints:
out f
If you leave out $length, substr(  ) returns the string from $start to the end of the original string, as shown in .
Example . Using substr(  ) with positive start and no length
print substr('watch out for that tree',17);
prints:
t tree
If $start is bigger than the length of the string, substr(  ) returns false..
If $start plus $length goes past the end of the string, substr(  ) returns all of the string from $start forward, as shown in .
Example . Using substr(  ) with length past the end of the string
print substr('watch out for that tree',20,5);
prints:
ree
If $start is negative, substr(  ) counts back from the end of the string to determine where your substring starts, as shown in .
Example . Using substr(  ) with negative start
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Replacing Substrings
You want to replace a substring with a different string. For example, you want to obscure all but the last four digits of a credit card number before printing it.
Use substr_replace(‏‎‎), as in .
Example . Replacing a substring with substr_replace(  )
// Everything from position $start to the end of $old_string
// becomes $new_substring
$new_string = substr_replace($old_string,$new_substring,$start);

// $length characters, starting at position $start, become $new_substring
$new_string = substr_replace($old_string,$new_substring,$start,$length);
Without the $length argument, substr_replace(  ) replaces everything from $start to the end of the string. If $length is specified, only that many characters are replaced:
print substr_replace('My pet is a blue dog.','fish.',12);
print substr_replace('My pet is a blue dog.','green',12,4);
$credit_card = '4111 1111 1111 1111';
print substr_replace($credit_card,'xxxx ',0,strlen($credit_card)-4);

My pet is a fish.
My pet is a green dog.
xxxx 1111
If $start is negative, the new substring is placed at $start characters counting from the end of $old_string, not from the beginning:
print substr_replace('My pet is a blue dog.','fish.',-9);
print substr_replace('My pet is a blue dog.','green',-9,4);

My pet is a fish.
My pet is a green dog.
If $start and $length are 0, the new substring is inserted at the start of $old_string:
print substr_replace('My pet is a blue dog.','Title: ',0,0);

Title: My pet is a blue dog.
The function substr_replace(  ) is useful when you’ve got text that’s too big to display all at once, and you want to display some of the text with a link to the rest. displays the first 25 characters of a message with an ellipsis after it as a link to a page that displays more text.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Processing a String One Byte at a Time
You need to process each byte in a string individually.
Loop through each byte in the string with for. counts the vowels in a string.
Example . Processing each byte in a string
<?php
$string = "This weekend, I'm going shopping for a pet chicken.";
$vowels = 0;
for ($i = 0, $j = strlen($string); $i < $j; $i++) {
    if (strstr('aeiouAEIOU',$string[$i])) {
        $vowels++;
    }
}
?>
Processing a string a character at a time is an easy way to calculate the “Look and Say” sequence, as shown in .
Example . The “Look and Say” sequence
<?php
function lookandsay($s) {
    // initialize the return value to the empty string
    $r = '';
    // $m holds the character we're counting, initialize to the first
    // character in the string
    $m = $s[0];
    // $n is the number of $m's we've seen, initialize to 1
    $n = 1;
    for ($i = 1, $j = strlen($s); $i < $j; $i++) {
        // if this character is the same as the last one
        if ($s[$i] == $m) {
            // increment the count of this character
            $n++;
        } else {
            // otherwise, add the count and character to the return value 
            $r .= $n.$m;
            // set the character we're looking for to the current one 
            $m = $s[$i];
            // and reset the count to 1
            $n = 1;
        }
    }
    // return the built up string as well as the last count and character
    return $r.$n.$m;
}

for ($i = 0, $s = 1; $i < 10; $i++) {
    $s = lookandsay($s);
    print "$s <br/>\n";
}
prints:
1
11
21
1211
111221
312211
13112221
1113213211
31131211131221
13211311123113112211
It’s called the “Look and Say” sequence because each element is what you get by looking at the previous element and saying what’s in it. For example, looking at the first element, 1, you say “one one.” So the second element is “11.” That’s two ones, so the third element is “21.” Similarly, that’s one two and one one, so the fourth element is “1211,” and so on.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Reversing a String by Word or Byte
You want to reverse the words or the bytes in a string.
Use strrev(  ) to reverse by byte, as in .
Example . Reversing a string by byte
<?php
print strrev('This is not a palindrome.');
?>
prints:
.emordnilap a ton si sihT
To reverse by words, explode the string by word boundary, reverse the words, and then rejoin, as in .
Example . Reversing a string by word
<?php
$s = "Once upon a time there was a turtle.";
// break the string up into words
$words = explode(' ',$s);
// reverse the array of words
$words = array_reverse($words);
// rebuild the string
$s = implode(' ',$words);
print $s;
?>
prints:
turtle. a was there time a upon Once
Reversing a string by words can also be done all in one line with the code in .
Example . Concisely reversing a string by word
<?php
$reversed_s = implode(' ',array_reverse(explode(' ',$s)));
?>
discusses the implications of using something other than a space character as your word boundary; documentation on strrev(  ) at http://www.php.net/strrev and array_reverse(  ) at http://www.php.net/array-reverse.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Expanding and Compressing Tabs
You want to change spaces to tabs (or tabs to spaces) in a string while keeping text aligned with tab stops. For example, you want to display formatted text to users in a standardized way.
Use str_replace(  ) to switch spaces to tabs or tabs to spaces, as shown in .
Example . Switching tabs and spaces
<?php
$r = mysql_query("SELECT message FROM messages WHERE id = 1") or die();
$ob = mysql_fetch_object($r);
$tabbed = str_replace(' ',"\t",$ob->message);
$spaced = str_replace("\t",' ',$ob->message);

print "With Tabs: <pre>$tabbed</pre>";
print "With Spaces: <pre>$spaced</pre>";
?>
Using str_replace(  ) for conversion, however, doesn’t respect tab stops. If you want tab stops every eight characters, a line beginning with a five-letter word and a tab should have that tab replaced with three spaces, not one. Use the pc_tab_expand(  ) function shown in into turn tabs to spaces in a way that respects tab stops.
Example . pc_tab_expand(  )
<?php
function pc_tab_expand($text) {
    while (strstr($text,"\t")) {
        $text = preg_replace_callback('/^([^\t\n]*)(\t+)/m','pc_tab_expand_helper', $text);
    }
    return $text;
}

function pc_tab_expand_helper($matches) {
    $tab_stop = 8;
    
    return $matches[1] .
    str_repeat(' ',strlen($matches[2]) * 
                       $tab_stop - (strlen($matches[1]) % $tab_stop));
}


$spaced = pc_tab_expand($ob->message);
?>
You can use the pc_tab_unexpand(  ) function shown in to turn spaces back to tabs.
Example . pc_tab_unexpand(  )
<?php
function pc_tab_unexpand($text) {
    $tab_stop = 8;
    $lines = explode("\n",$text);
    foreach ($lines as $i => $line) {
        // Expand any tabs to spaces
        $line = pc_tab_expand($line);
        $chunks = str_split($line, $tab_stop);
        $chunkCount = count($chunks);
        // Scan all but the last chunk
        for ($j = 0; $j < $chunkCount - 1; $j++) {
            $chunks[$j] = preg_replace('/ {2,}$/',"\t",$chunks[$j]);
        }
        // If the last chunk is a tab-stop's worth of spaces
        // convert it to a tab; Otherwise, leave it alone
        if ($chunks[$chunkCount-1] == str_repeat(' ', $tab_stop)) {
            $chunks[$chunkCount-1] = "\t";
        }
        // Recombine the chunks
        $lines[$i] = implode('',$chunks);
    }
    // Recombine the lines
    return implode("\n",$lines);
}

$tabbed = pc_tab_unexpand($ob->message);
?>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Controlling Case
You need to capitalize, lowercase, or otherwise modify the case of letters in a string. For example, you want to capitalize the initial letters of names but lowercase the rest.
Use ucfirst(  ) or ucwords(  ) to capitalize the first letter of one or more words, as shown in .
Example . Capitalizing letters
<?php
print ucfirst("how do you do today?");
print ucwords("the prince of wales");
?>
prints:
How do you do today?
The Prince Of Wales
Use strtolower(  ) or strtoupper(  ) to modify the case of entire strings, as in .
Example . Changing case of strings
print strtoupper("i'm not yelling!");
// Tags must be lowercase to be XHTML compliant
print strtolower('<A HREF="one.php">one</A>');
prints:
I'M NOT YELLING!
<a href="one.php">one</a>
Use ucfirst(  ) to capitalize the first character in a string:
<?php
print ucfirst('monkey face');
print ucfirst('1 monkey face');
?>
This prints:
Monkey face
1 monkey face
Note that the second phrase is not “1 Monkey face.”
Use ucwords(  ) to capitalize the first character of each word in a string:
<?php
print ucwords('1 monkey face');
print ucwords("don't play zone defense against the philadelphia 76-ers");
?>
This prints:
1 Monkey Face
Don't Play Zone Defense Against The Philadelphia 76-ers
As expected, ucwords(  ) doesn’t capitalize the “t” in “don’t.” But it also doesn’t capitalize the “e” in “76-ers.” For ucwords(  ), a word is any sequence of nonwhitespace characters that follows one or more whitespace characters. Since both ' and - aren’t whitespace characters,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Interpolating Functions and Expressions Within Strings
You want to include the results of executing a function or expression within a string.
Use the string concatenation operator (.), as shown in , when the value you want to include can’t be inside the string.
Example . String concatenation
<?php
print 'You have '.($_REQUEST['boys'] + $_REQUEST['girls']).' children.';
print "The word '$word' is ".strlen($word).' characters long.';
print 'You owe '.$amounts['payment'].' immediately';
print "My circle's diameter is ".$circle->getDiameter().' inches.';
?>
You can put variables, object properties, and array elements (if the subscript is unquoted) directly in double-quoted strings:
<?php
print "I have $children children.";
print "You owe $amounts[payment] immediately.";
print "My circle's diameter is $circle->diameter inches.";
?>
Interpolation with double-quoted strings places some limitations on the syntax of what can be interpolated. In the previous example, $amounts['payment'] had to be written as $amounts[payment] so it would be interpolated properly. Use curly braces around more complicated expressions to interpolate them into a string. For example:
<?php
print "I have less than {$children} children.";
print "You owe {$amounts['payment']} immediately.";
print "My circle's diameter is {$circle->getDiameter()} inches.";
?>
Direct interpolation or using string concatenation also works with heredocs. Interpolating with string concatenation in heredocs can look a little strange because the closing heredoc delimiter and the string concatenation operator have to be on separate lines:
<?php
print <<< END
Right now, the time is 
END
. strftime('%c') . <<< END
 but tomorrow it will be 
END
. strftime('%c',time() + 86400);
?>
Also, if you’re interpolating with heredocs, make sure to include appropriate spacing for the whole string to appear properly. In the previous example,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Trimming Blanks from a String
You want to remove whitespace from the beginning or end of a string. For example, you want to clean up user input before validating it.
Use ltrim(  ), rtrim(  ), or trim(  ). ltrim(  ) removes whitespace from the beginning of a string, rtrim(  ) from the end of a string, and trim(  ) from both the beginning and end of a string:
<?php
$zipcode = trim($_REQUEST['zipcode']);
$no_linefeed = rtrim($_REQUEST['text']);
$name = ltrim($_REQUEST['name']);
?>
For these functions, whitespace is defined as the following characters: newline, carriage return, space, horizontal and vertical tab, and null.
Trimming whitespace off of strings saves storage space and can make for more precise display of formatted data or text within <pre> tags, for example. If you are doing comparisons with user input, you should trim the data first, so that someone who mistakenly enters “98052” as their zip code isn’t forced to fix an error that really isn’t one. Trimming before exact text comparisons also ensures that, for example, “salami\n” equals “salami.” It’s also a good idea to normalize string data by trimming it before storing it in a database.
The trim(  ) functions can also remove user-specified characters from strings. Pass the characters you want to remove as a second argument. You can indicate a range of characters with two dots between the first and last characters in the range:
<?php
// Remove numerals and space from the beginning of the line
print ltrim('10 PRINT A$',' 0..9');
// Remove semicolon from the end of the line
print rtrim('SELECT * FROM turtles;',';');
?>
This prints:
PRINT A$
SELECT * FROM turtles
PHP also provides chop(  )
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Generating Comma-Separated Data
You want to format data as comma-separated values (CSV) so that it can be imported by a spreadsheet or database.
Use the fputcsv(  ) function to generate a CSV-formatted line from an array of data. writes the data in $sales into a file.
Example . Generating comma-separated data
<?php

$sales = array( array('Northeast','2005-01-01','2005-02-01',12.54),
                array('Northwest','2005-01-01','2005-02-01',546.33),
                array('Southeast','2005-01-01','2005-02-01',93.26),
                array('Southwest','2005-01-01','2005-02-01',945.21),
                array('All Regions','--','--',1597.34) );

$fh = fopen('sales.csv','w') or die("Can't open sales.csv");
foreach ($sales as $sales_line) {
    if (fputcsv($fh, $sales_line) === false) {
        die("Can't write CSV line");
    }
}
fclose($fh) or die("Can't close sales.csv");

?>
To print the CSV-formatted data instead of writing it to a file, use the special output stream php://output , as shown in .
Example . Printing comma-separated data
<?php

$sales = array( array('Northeast','2005-01-01','2005-02-01',12.54),
                array('Northwest','2005-01-01','2005-02-01',546.33),
                array('Southeast','2005-01-01','2005-02-01',93.26),
                array('Southwest','2005-01-01','2005-02-01',945.21),
                array('All Regions','--','--',1597.34) );

$fh = fopen('php://output','w');
foreach ($sales as $sales_line) {
    if (fputcsv($fh, $sales_line) === false) {
        die("Can't write CSV line");
    }
}
fclose($fh);
?>
To put the CSV-formatted data into a string instead of printing it or writing it to a file, combine the technique in with output buffering, as shown in .
Example . Putting comma-separated data into a string
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Parsing Comma-Separated Data
You have data in comma-separated values (CSV) format—for example, a file exported from Excel or a database—and you want to extract the records and fields into a format you can manipulate in PHP.
If the CSV data is in a file (or available via a URL), open the file with fopen(  ) and read in the data with fgetcsv(  ) . prints out CSV data in an HTML table.
Example . Reading CSV data from a file
<?php
$fp = fopen('sample2.csv','r') or die("can't open file");
print "<table>\n";
while($csv_line = fgetcsv($fp)) {
    print '<tr>';
    for ($i = 0, $j = count($csv_line); $i < $j; $i++) {
        print '<td>'.htmlentities($csv_line[$i]).'</td>';
    }
    print "</tr>\n";
}
print '</table>\n';
fclose($fp) or die("can't close file");
?>
In PHP 4, you must provide a second argument to fgetcsv(  ) that is a value larger than the maximum length of a line in your CSV file. (Don’t forget to count the end-of-line whitespace.) In PHP 5 the line length is optional. Without it, fgetcsv(  ) reads in an entire line of data. (Or, in PHP 5.0.4 and later, you can pass a line length of 0 to do the same thing.) If your average line length is more than 8,192 bytes, your program may run faster if you specify an explicit line length instead of letting PHP figure it out.
You can pass fgetcsv(  ) an optional third argument, a delimiter to use instead of a comma (,). However, using a different delimiter somewhat defeats the purpose of CSV as an easy way to exchange tabular data.
Don’t be tempted to bypass fgetcsv(  ) and just read a line in and explode(  ) on the commas. CSV is more complicated than that, able to deal with field values that have, for example, literal commas in them that should not be treated as field delimiters. Using
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Generating Fixed-Width Field Data Records
You need to format data records such that each field takes up a set amount of characters.
Use pack(  ) with a format string that specifies a sequence of space-padded strings. transforms an array of data into fixed-width records.
Example . Generating fixed-width field data records
<?php

$books = array( array('Elmer Gantry', 'Sinclair Lewis', 1927),
                array('The Scarlatti Inheritance','Robert Ludlum',1971),
                array('The Parsifal Mosaic','William Styron',1979) );

foreach ($books as $book) {
    print pack('A25A15A4', $book[0], $book[1], $book[2]) . "\n";
}

?>
The format string A25A14A4 tells pack(  ) to transform its subsequent arguments into a 25-character space-padded string, a 14-character space-padded string, and a 4-character space-padded string. For space-padded fields in fixed-width records, pack(  ) provides a concise solution.
To pad fields with something other than a space, however, use substr(  ) to ensure that the field values aren’t too long and str_pad(  ) to ensure that the field values aren’t too short. transforms an array of records into fixed-width records with .⁠-⁠padded fields.
Example . Generating fixed-width field data records without pack(  )
<?php

$books = array( array('Elmer Gantry', 'Sinclair Lewis', 1927),
                array('The Scarlatti Inheritance','Robert Ludlum',1971),
                array('The Parsifal Mosaic','William Styron',1979) );

foreach ($books as $book) {
    $title  = str_pad(substr($book[0], 0, 25), 25, '.');
    $author = str_pad(substr($book[1], 0, 15), 15, '.');
    $year   = str_pad(substr($book[2], 0, 4), 4, '.');
    print "$title$author$year\n";
}

?>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Parsing Fixed-Width Field Data Records
You need to break apart fixed-width records in strings.
Use substr(  ) as shown in .
Example . Parsing fixed-width records with substr(  )
<?php
$fp = fopen('fixed-width-records.txt','r') or die ("can't open file");
while ($s = fgets($fp,1024)) {
    $fields[1] = substr($s,0,10);  // first field:  first 10 characters of the line
    $fields[2] = substr($s,10,5);  // second field: next 5 characters of the line
    $fields[3] = substr($s,15,12); // third field:  next 12 characters of the line
    // a function to do something with the fields
    process_fields($fields);
}
fclose($fp) or die("can't close file");
?>
Or unpack(  ) , as shown in .
Example . Parsing fixed-width records with unpack(  )
<?php
$fp = fopen('fixed-width-records.txt','r') or die ("can't open file");
while ($s = fgets($fp,1024)) {
    // an associative array with keys "title", "author", and "publication_year"
    $fields = unpack('A25title/A14author/A4publication_year',$s);
    // a function to do something with the fields
    process_fields($fields);
}
fclose($fp) or die("can't close file");
?>
Data in which each field is allotted a fixed number of characters per line may look like this list of books, titles, and publication dates:
<?php
$booklist=<<<END
Elmer Gantry             Sinclair Lewis1927
The Scarlatti InheritanceRobert Ludlum 1971
The Parsifal Mosaic      Robert Ludlum 1982
Sophie's Choice          William Styron1979
END;
?>
In each line, the title occupies the first 25 characters, the author’s name the next 14 characters, and the publication year the next 4 characters. Knowing those field widths, you can easily use substr(  ) to parse the fields into an array:
<?php
$books = explode("\n",$booklist);

for($i = 0, $j = count($books); $i < $j; $i++) {
  $book_array[$i]['title'] = substr($books[$i],0,25);
  $book_array[$i]['author'] = substr($books[$i],25,14);
  $book_array[$i]['publication_year'] = substr($books[$i],39,4);
}
?>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Taking Strings Apart
You need to break a string into pieces. For example, you want to access each line that a user enters in a <textarea> form field.
Use explode(  ) if what separates the pieces is a constant string:
<?php
$words = explode(' ','My sentence is not very complicated');
?>
Use split(  ) or preg_split(  ) if you need a POSIX or Perl-compatible regular expression to describe the separator:
<?php
$words = split(' +','This sentence  has  some extra whitespace  in it.');
$words = preg_split('/\d\. /','my day: 1. get up 2. get dressed 3. eat toast');
$lines = preg_split('/[\n\r]+/',$_REQUEST['textarea']);
?>
Use spliti(  ) or the /i flag to preg_split(  ) for case-insensitive separator matching:
<?php
$words = spliti(' x ','31 inches x 22 inches X 9 inches');
$words = preg_split('/ x /i','31 inches x 22 inches X 9 inches');
?>
The simplest solution of the bunch is explode(  ). Pass it your separator string, the string to be separated, and an optional limit on how many elements should be returned:
<?php
$dwarves = 'dopey,sleepy,happy,grumpy,sneezy,bashful,doc';
$dwarf_array = explode(',',$dwarves);
?>
This makes $dwarf_array a seven-element array, so print_r($dwarf_array) prints:
Array
(
    [0] => dopey
    [1] => sleepy
    [2] => happy
    [3] => grumpy
    [4] => sneezy
    [5] => bashful
    [6] => doc
)
If the specified limit is less than the number of possible chunks, the last chunk contains the remainder:
<?php
$dwarf_array = explode(',',$dwarves,5);
print_r($dwarf_array);
?>
This prints:
Array
(
    [0] => dopey
    [1] => sleepy
    [2] => happy
    [3] => grumpy
    [4] => sneezy,bashful,doc
)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Wrapping Text at a Certain Line Length
You need to wrap lines in a string. For example, you want to display text in <pre>/</pre> tags but have it stay within a regularly sized browser window.
Use wordwrap(  ) :
<?php
$s = "Four score and seven years ago our fathers brought forth↵
on this continent a new nation, conceived in liberty and↵
dedicated to the proposition that all men are created equal.";

print "<pre>\n".wordwrap($s)."\n</pre>";
?>
This prints:
<pre>
Four score and seven years ago our fathers brought forth on this continent
a new nation, conceived in liberty and dedicated to the proposition that
all men are created equal.
</pre>
By default, wordwrap(  ) wraps text at 75 characters per line. An optional second argument specifies different line length:
<?php
print wordwrap($s,50);
?>
This prints:
Four score and seven years ago our fathers brought
forth on this continent a new nation, conceived in
liberty and dedicated to the proposition that all
men are created equal.
Other characters besides \n can be used for line breaks. For double spacing, use "\n\n":
<?php
print wordwrap($s,50,"\n\n");
?>
This prints:
Four score and seven years ago our fathers brought

forth on this continent a new nation, conceived in

liberty and dedicated to the proposition that all

men are created equal.
There is an optional fourth argument to wordwrap(  ) that controls the treatment of words that are longer than the specified line length. If this argument is 1, these words are wrapped. Otherwise, they span past the specified line length:
<?php
print wordwrap('jabberwocky',5);
print wordwrap('jabberwocky',5,"\n",1);
?>
This prints:
jabberwocky

jabbe
rwock
y
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Storing Binary Data in Strings
You want to parse a string that contains values encoded as a binary structure or encode values into a string. For example, you want to store numbers in their binary representation instead of as sequences of ASCII characters.
Use pack(  ) to store binary data in a string:
<?php
$packed = pack('S4',1974,106,28225,32725);
?>
Use unpack(  ) to extract binary data from a string:
<?php
$nums = unpack('S4',$packed);
?>
The first argument to pack(  ) is a format string that describes how to encode the data that’s passed in the rest of the arguments. The format string S4 tells pack(  ) to produce four unsigned short 16-bit numbers in machine byte order from its input data. Given 1974, 106, 28225, and 32725 as input on a little-endian machine, this returns eight bytes: 182, 7, 106, 0, 65, 110, 213, and 127. Each two-byte pair corresponds to one of the input numbers: 7 * 256 + 182 is 1974; 0 * 256 + 106 is 106; 110 * 256 + 65 = 28225; 127 * 256 + 213 = 32725.
The first argument to unpack(  ) is also a format string, and the second argument is the data to decode. Passing a format string of S4, the eight-byte sequence that pack(  ) produced returns a four-element array of the original numbers. print_r($nums) prints:
Array
(
    [1] => 1974
    [2] => 106
    [3] => 28225
    [4] => 32725
)
In unpack(  ), format characters and their count can be followed by a string to be used as an array key. For example:
<?php
$nums = unpack('S4num',$packed);
print_r($nums);
?>
This prints:
Array
(
    [num1] => 1974
    [num2] => 106
    [num3] => 28225
    [num4] => 32725
)
Multiple format characters must be separated with / in unpack(  ):
<?php
$nums = unpack('S1a/S1b/S1c/S1d',$packed);
print_r($nums);
?>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Program: Downloadable CSV File
Combining the header(  ) function to change the content type of what your PHP program outputs with the fputcsv(  ) function for data formatting lets you send CSV files to browsers that will be automatically handed off to a spreadsheet program (or whatever application is configured on a particular client system to handle CSV files). formats the results of an SQL SELECT query as CSV data and provides the correct headers so that it is properly handled by the browser.
Example . Downloadable CSV file
<?php

require_once 'DB.php';
// Connect to the database
$db = DB::connect('mysql://david:hax0r@localhost/phpcookbook');

// Retrieve data from the database
$sales_data = $db->getAll('SELECT region, start, end, amount FROM sales');
// Open filehandle for fputcsv()
$output = fopen('php://output','w') or die("Can't open php://output");
$total = 0;

// Tell browser to expect a CSV file
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="sales.csv"');

// Print header row
fputcsv($output,array('Region','Start Date','End Date','Amount'));
// Print each data row and increment $total
foreach ($sales_data as $sales_line) {
    fputcsv($output, $sales_line);
    $total += $sales_line[3];
}
// Print total row and close file handle
fputcsv($output,array('All Regions','--','--',$total));
fclose($output) or die("Can't close php://output");

?>
sends two headers to ensure that the browser handles the CSV output properly. The first header, Content-Type, tells the browser that the output is not HTML, but CSV. The second header, Content-Disposition, tells the browser not to display the output but to attempt to load an external program to handle it. The filename attribute of this header supplies a default filename for the browser to use for the downloaded file.
If you want to provide different views of the same data, you can combine the formatting code in one page and use a query string variable to determine which kind of data formatting to do. In , the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Numbers
In everyday life, numbers are easy to identify. They’re 3:00 P.M., as in the current time, or $1.29, as in the cost of a pint of milk. Maybe they’re like π, the ratio of the circumference to the diameter of a circle. They can be pretty large, like Avogadro’s number, which is about 6 × 1023. In PHP, numbers can be all these things.
However, PHP doesn’t treat all these numbers as “numbers.” Instead, it breaks them down into two groups: integers and floating-point numbers. Integers are whole numbers, such as 4, 0, 5, and 1,975. Floating-point numbers are decimal numbers, such as 1.23, 0.0, 3.14159, and 9.9999999999.
Conveniently, most of the time PHP doesn’t make you worry about the differences between the two because it automatically converts integers to floating-point numbers and floating-point numbers to integers. This conveniently allows you to ignore the underlying details. It also means 3/2 is 1.5, not 1, as it would be in some programming languages. PHP also automatically converts from strings to numbers and back. For instance, 1+"1" is 2.
However, sometimes this blissful ignorance can cause trouble. First, numbers can’t be infinitely large or small; there’s a minimum size of 2.2e308 and a maximum size of about 1.8e308. If you need larger (or smaller) numbers, you must use the BCMath or GMP libraries, which are discussed in .
Next, floating-point numbers aren’t guaranteed to be exactly correct but only correct plus or minus a small amount. This amount is small enough for most occasions, but you can end up with problems in certain instances. For instance, humans automatically convert 6 followed by an endless string of 9s after the decimal point to 7, but PHP thinks it’s 6 with a bunch of 9s. Therefore, if you ask PHP for the integer value of that number, it returns 6, not 7. For similar reasons, if the digit located in the 200th decimal place is significant to you, don’t use floating-point numbers—instead, use the BCMath and GMP libraries. But for most occasions, PHP behaves very nicely when playing with numbers and lets you treat them just as you do in real life.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
In everyday life, numbers are easy to identify. They’re 3:00 P.M., as in the current time, or $1.29, as in the cost of a pint of milk. Maybe they’re like π, the ratio of the circumference to the diameter of a circle. They can be pretty large, like Avogadro’s number, which is about 6 × 1023. In PHP, numbers can be all these things.
However, PHP doesn’t treat all these numbers as “numbers.” Instead, it breaks them down into two groups: integers and floating-point numbers. Integers are whole numbers, such as 4, 0, 5, and 1,975. Floating-point numbers are decimal numbers, such as 1.23, 0.0, 3.14159, and 9.9999999999.
Conveniently, most of the time PHP doesn’t make you worry about the differences between the two because it automatically converts integers to floating-point numbers and floating-point numbers to integers. This conveniently allows you to ignore the underlying details. It also means 3/2 is 1.5, not 1, as it would be in some programming languages. PHP also automatically converts from strings to numbers and back. For instance, 1+"1" is 2.
However, sometimes this blissful ignorance can cause trouble. First, numbers can’t be infinitely large or small; there’s a minimum size of 2.2e308 and a maximum size of about 1.8e308. If you need larger (or smaller) numbers, you must use the BCMath or GMP libraries, which are discussed in .
Next, floating-point numbers aren’t guaranteed to be exactly correct but only correct plus or minus a small amount. This amount is small enough for most occasions, but you can end up with problems in certain instances. For instance, humans automatically convert 6 followed by an endless string of 9s after the decimal point to 7, but PHP thinks it’s 6 with a bunch of 9s. Therefore, if you ask PHP for the integer value of that number, it returns 6, not 7. For similar reasons, if the digit located in the 200th decimal place is significant to you, don’t use floating-point numbers—instead, use the BCMath and GMP libraries. But for most occasions, PHP behaves very nicely when playing with numbers and lets you treat them just as you do in real life.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Checking Whether a Variable Contains a Valid Number
You want to ensure that a variable contains a number, even if it’s typed as a string. Alternatively, you want to check if a variable is not only a number, but is also specifically typed as a one.
Use is_numeric(  ) to discover whether a variable contains a number:
<?php
if (is_numeric(5))          { /* true  */ }
if (is_numeric('5'))        { /* true  */ }
if (is_numeric("05"))       { /* true  */ }
if (is_numeric('five'))     { /* false */ }

if (is_numeric(0xDECAFBAD)) { /* true  */ }
if (is_numeric("10e200"))   { /* true  */ }
?>
Numbers come in all shapes and sizes. You cannot assume that something is a number simply because it only contains the characters 0 through 9. What about decimal points, or negative signs? You can’t simply add them into the mix because the negative must come at the front, and you can only have one decimal point. And then there’s hexadecimal numbers and scientific notation.
Instead of rolling your own function, use is_numeric(  ) to check whether a variable holds something that’s either an actual number (as in it’s typed as an integer or floating point), or it’s a string containing characters that can be translated into a number.
There’s an actual difference here. Technically, the integer 5 and the string 5 aren’t the same in PHP. However, most of the time you won’t actually be concerned about the distinction, which is why the behavior of is_numeric(  ) is useful.
Helpfully, is_numeric(  ) properly parses decimal numbers, such as 5.1; however, numbers with thousands separators, such as 5,100, cause is_numeric(  ) to return false.
To strip the thousands separators from your number before calling is_numeric(  ), use str_replace(  ):
<?php
is_numeric(str_replace($number, ',', ''));
?>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Comparing Floating-Point Numbers
You want to check whether two floating-point numbers are equal.
Use a small delta value, and check if the numbers have a difference smaller than that delta:
<?php
$delta = 0.00001;

$a = 1.00000001;
$b = 1.00000000;

if (abs($a - $b) < $delta) { /* $a and $b are equal */ }
?>
Floating-point numbers are represented in binary form with only a finite number of bits for the mantissa and the exponent. You get overflows when you exceed those bits. As a result, sometimes PHP (just like some other languages) doesn’t believe that two equal numbers are actually equal because they may differ toward the very end.
To avoid this problem, instead of checking if $a == $b, make sure the first number is within a very small amount ($delta) of the second one. The size of your delta should be the smallest amount of difference you care about between two numbers. Then use abs(  ) to get the absolute value of the difference.
for information on rounding floating-point numbers; documentation on floating-point numbers in PHP at http://www.php.net/language.types.float.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Rounding Floating-Point Numbers
Content preview·