PHP – Greatest Hits Vol. I

Solid Gold PHP

Herein lies my favourite moments in PHP Rock n Roll history. Reader, please beware: this Warning.

fgetcsv() | Use PHP to Read a CSV File:
The following is copied from an example use of fgetcsv(), originally published at http://php.net/fgetcsv

fgetcsv() :: Example 617.

Read and print the entire contents of a CSV file
Reprinted here from the PHP Manual, as a personal, quick-reference. This note, intended for the author of this web log, has been reproduced without authorization from the original publisher, PHP.NET :

<?php
$row = 1;
$handle = fopen("test.csv", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
 for ($c=0; $c < $num; $c++) {
  echo $data[$c] . "<br />\n";
 }
}
fclose($handle);
?>

str_replace() | ucwords()

The following code snippet, using str_replace is handy for creating titles, names, or words in general from file names. The str_replace function, as shown, removes the underscore [ _ ] character, often used to replace spaces for file names (for avoiding filenames with space characters, a recommended practice), and replaces it in the visible text with a space. Then the function ucwords() capitalizes each word of the string, sometimes known as “Title Case”. It works very well!

$process = $_SERVER['PHP_SELF'];
$patharray = pathinfo($process);
$thispage = rtrim($patharray['basename'], $patharray['extension']);

$thispage_rtrim = rtrim($thispage, '.');
$replaced = str_replace("_", " ", $thispage_rtrim);

$bodyid = $thispage_rtrim;
$bodyUcWords = ucwords($replaced);
preg_replace()

The following snippet shows an instance of the use of preg_replace() in which any string (in this case, a word) with an “S” at the end would have that letter stripped from the string:

$subject=$xtraHead;
$pattern = '/([\w])([^s]?)$/';
$replace = '';
$xxHead=preg_replace($pattern, $replace, $subject);

substr

(PHP 4, PHP 5)

substr — Return part of a string

Description

string substr ( string $string, int $start [, int $length] )

substr() returns the portion of string
specified by the start and
length parameters(1).

If start is non-negative, the returned string
will start at the start‘th position in
string, counting from zero. For instance,
in the string ‘abcdef‘, the character at
position 0 is ‘a‘, the
character at position 2 is
c‘, and so forth.

Assignment Operators

[ . . . SNIP . . . ]

In addition to the basic assignment operator, there are “combined
operators” for all of the binary
arithmetic
, array union and string operators that allow you to use a value in an
expression and then set its value to the result of that expression. For
example:


<?php

$a = 3;

$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
$b = "Hello ";
$b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";

?>

Note that the assignment copies the original variable to the new
one (assignment by value), so changes to one will not affect the
other. This may also have relevance if you need to copy something
like a large array inside a tight loop. Since PHP 4, assignment
by reference has been supported, using the $var =
&$othervar;
syntax, but this is not possible
in PHP 3. ‘Assignment by reference’ means that both variables end
up pointing at the same data, and nothing is copied anywhere.
To learn more about references, please read References explained. As of PHP 5, objects are assigned by reference unless explicitly told otherwise with the new clone keyword.

Function arguments

Information may be passed to functions via the argument list,
which is a comma-delimited list of expressions.

PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are supported only in PHP 4 and later; see Variable-length argument lists and the function references for func_num_args(), func_get_arg(), and func_get_args() for more information. A similar effect can be achieved in PHP 3 by passing an array of arguments to a function:

Example 17.5. Passing arrays to functions


<?php
function takes_array($input)
{
echo
"$input[0] + $input[1] =", $input[
0]+
$input[ "default">1];
}
?>


Making
arguments be passed by reference

By default, function arguments are passed by value (so that if you
change the value of the argument within the function, it does not
get changed outside of the function). If you wish to allow a
function to modify its arguments, you must pass them by reference.

If you want an argument to a function to always be passed by
reference, you can prepend an ampersand (&) to the argument
name in the function definition:

Example 17.6. Passing function parameters by reference

<?php
function add_some_extra(&$string)
{
$string .= 'and something
extra.'
;
}
$str = 'This is a string,
'
;
add_some_extra($str);
echo
$str; // outputs 'This is
a string, and something extra.'
?>


Default argument
values

A function may define C++-style default values for scalar arguments
as follows:

Example 17.7. Use of default parameters in functions

<?php
function makecoffee($type = "cappuccino")
{
return
"Making a cup of
$type.\n"
;
}
echo
makecoffee();
echo
makecoffee(null);
echo
makecoffee("espresso");
?>


The output from the above snippet is:

Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

Also PHP allows you to use arrays and special type NULL as default
values, for example:

Example 17.8. Using non-scalar types as default values

<?php
function makecoffee($types
= array("cappuccino"),
$coffeeMaker = NULL)
{
$device = is_null($coffeeMaker)
?
"hands" : $coffeeMaker;
return
"Making a cup of
"
.join(", ", $types)." with
$device.\n"
;
}
echo
makecoffee();
echo
makecoffee(array("cappuccino",
"lavazza"), "teapot");
?>


The default value must be a constant expression, not (for
example) a variable, a class member or a function call.


*Reader Beware This is not an authoritative source! The examples, illustrations, and any other text here may resemble the PHP Manual but should not be mistakenly used as a shortcut for first studying the primary, official resource for PHP facts. Some of what is recorded here may be snippets of html markup appropriated directly from some source-code of the Official On-line PHP Documentation at www.PHP.net, however the author of this abbreviated reference asks that you use it only for your own recollection of basic concepts. Please do not use appropriated material‡ as an alternative to any official, comprehensive documentation. A sharp reader should cross-reference the corresponding section of the PHP manual. Locate the term of your interest in the official documentation by going to the online manual and using php.net integrated php functions search engine (top right of the portal).

‡ Appropriated media is reprinted from an original source in an unofficial form, cited but unauthorized by the original Author. It’s important to recognize that any unauthorized reproductions of original source media (text, video, audio, etc.), especially when a reproduction has not cited the original source, the reproduced material, for all intents and purposes, should be considered as stolen.

1String Functions: substr. the PHP Manual. the PHP Group. Rev. Apr 14, 2007. Available at: http://www.php.net/manual/en/function.substr.php . Accessed: April 14, 2007.