PHP Aide-Memoire
Just that. A memory-jogger for someone (like me) who uses PHP scripts in the construction of websites, but not frequently enough to guarantee that the precise syntax will always unfailingly trip off the tongue at a moment's notice. The examples given are ones that I've used, and of course there are many others. This resource is mainly for my own use but may be helpful as a quick reference for other designers who enjoy the magic of PHP.
Strings
Also (lower on the page): arrays, patterns, files, MySQL queries, functions.
Access individual characters in a string:
$string = "characters"; echo $string[2]; // a
Check for a string (2) in another string (1):
if (strstr($string1, $string2)) {
// do something...
}
Locate the position of a substring in a string:
// Example 1
$string = 'characters';
$find = 'act';
$pos = strpos($string, $find);
if ($pos === false) { // Note triple equals
echo "'$find' was not found in '$string'";
} else {
echo "'$find' was found in '$string' at position $pos";
}
// Example 2
$string = "abcdef abcdef";
$pos = strpos($string, "a", 1); // $pos = 7, not 0
// Example 3
$string = "pippa999female";
if (strpos($string, "pippa") === 0) {
echo "Hello Pippa";
}
Check the length of a string:
if (strlen($string) == 0) { // If there isn't a string
// do something...
}
Trim whitespace at each end of a string:
$string = trim($string);
Get a specified portion of a string:
$string = "the cat sat on the mat"; // Get 3 characters from character 5 echo substr($string, 5, 3); // cat // Get the last 3 characters echo substr($string, -3); // mat // Get the last 3 characters but 4 echo substr($string, -7, 3); // the
Repeat a string a specified number of times:
$string = "ha"; // Note: str_repeat includes the original instance echo str_repeat($string, 6); // hahahahahaha
Strip HTML tags from a string:
$cleanText = strip_tags($text); // To allow specified tags: $allowedTags = 'write the (opening) tags'; $cleanText = strip_tags($text, $allowedTags);
Convert case:
$string = "aLExAnDeR tHE grEAt"; // First make all lowercase, then make first letters cap $string = ucwords(strtolower($string)); echo $string; // Alexander The Great // There is also strtoupper()
Count the number of words in a string:
$number = str_word_count($string);
Replace one instance of part of a string with something else:
$string = "pippa999female"; // Starting position = 5, length of instance = 3 $string = substr_replace($string, "1000", 5, 3); echo "You are $string."; // You are pippa1000female.
Replace all instances of part of a string:
$inThis = str_replace("Replace this", "With this", $inThis);
Arrays
Create and access an enumerated array:
$myArray = array('John', 'Paul', 'George', 'Ringo');
echo $myArray[0]; // John
echo $myArray[3]; // Ringo
// Loop through the array to print all
foreach ($myArray as $val) {
echo "$val "; // John Paul George Ringo
}
Create and access an associative array:
$myArray = array(
"rhythm" => "John",
"bass" => "Paul",
"lead" => "George",
"drums" => "Ringo"
}
echo $myArray["bass"]; // Paul
// Loop through the array to print all
foreach ($myArray as $key=>$val) {
echo "$key: $val "; // rhythm: John bass: Paul etc
}
Split a string into an array using a separator:
// Example 1
$string = "the cat sat on the mat";
$myArray = explode(" ", $string); // Separator = " "
echo $myArray[0]; // the
echo $myArray[2]; // sat
// Example 2
$string = "less|is|more";
list($one, $two, $three) = explode("|", $string);
echo $one; // less
echo $three; // more
// Note that 'list' assigns a list of variables, eg:
$myArray = array('less', 'is', 'more');
// Get some
list($one, , $three) = $myArray;
echo "$three is not $one"; // more is not less
Make a string from an array, with glue in between:
$myArray = array("John", "Paul", "George", "Ringo");
// Glue = comma + space
echo implode(", ", $myArray); // John, Paul, George, Ringo
Extract only a specified part of an array:
$myArray = array("John", "Paul", "George", "Ringo");
// Example 1: start at element 3
$slice = array_slice($myArray, 2);
foreach ($slice as $val) {
echo "$val "; // George Ringo
}
// Example 2: start two from the end and return one
$slice = array_slice($myArray, -2, 1);
foreach ($slice as $val) {
echo "$val "; // George
}
// Example 3: start at the beginning and return two
$slice = array_slice($myArray, 0, 2);
foreach ($slice as $val) {
echo "$val "; // John Paul
}
Multiple search and replace:
// Create an array of source strings
$myArray = array("less is more", "John Paul George Ringo");
// Create arrays of search and replace strings
$search = array("less", "more", "Ringo");
$replace = array("more", "less", "Pete");
// Replace and display
$myArray = str_replace($search, $replace, $myArray);
foreach($myArray as $string) {
echo "$string, "; // more is less, John Paul George Pete
}
Patterns
Replace a pattern in a string:
// Example 1
// Pattern = a regular expression
$string = preg_replace('/pattern/', "new", $string);
// Example 2 - case insensitive
$string = eregi_replace('/pattern/', "new", $string);
Check for a (first) match in a string:
// Pattern = a regular expression
if (preg_match("/pattern/", $string)) {
// If a match was found
// do something...
} else {
// do something else...
}
Files
Create and delete a file:
touch("myfile.txt"); // Create a file
unlink("myfile.txt"); // Delete a file
Read and display the contents of a file:
// Example 1
if (file_exists($filename)) {
$file_contents = file_get_contents($filename);
echo $file_contents;
}
// Example 2
// Return an array with each line as an element
$fileArray = file("myfile.txt");
// Do something useful with the array - not just:
$file_contents = implode($fileArray);
echo $file_contents;
Write to a file:
$filename = "myfile.txt"; // File must be writable
$fp = fopen($filename, "w") or die("Error!");
fwrite($fp, "Some content to be written.");
fclose($fp);
// The above overwrites the whole file
// To append to the file, use "a" instead of "w"
List the contents of a folder:
$dirname = "path/folder/";
$dh = opendir($dirname);
while (false !== ($file = readdir($dh))) {
if (is_dir("$dirname/$file")) {
echo "(Folder) ";
}
echo "$file, ";
}
closedir($dh);
Output 'readdir' file list alphabetically:
$dirname = "path/folder/";
if ($folder = opendir($dirname)) {
$filesArray = array();
while (false !== ($file = readdir($folder))) {
// Add each file to array
$filesArray[] = $file;
}
// Sort array alphabetically
natcasesort($filesArray);
// Output list
foreach ($filesArray as $file) {
echo "$file, ";
}
closedir($folder);
}
MySQL queries
Query using mysql_fetch_array:
// Example 1 - with MYSQL_NUM
// Open the database connection
// Build the query
$query = "SELECT field1, field2, field3 FROM table DESC";
// Run the query
$result = @mysql_query($query);
if ($result) { // If it ran OK
// Loop through the records and print
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo $row[0] . ' ' . $row[1] . ' ' . $row[2] . ' ';
}
} else {
echo "No results found.";
}
// Free up the resources
mysql_free_result($result);
// Close the database connection
// Example 2 - with MYSQL_ASSOC (associative array)
$query = "SELECT field1, field2, field3 FROM table DESC";
$result = @mysql_query($query);
if ($result) {
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "$row[field1] $row[field2] $row[field3]";
}
}
Also count the rows using mysql_num_rows:
$query = "SELECT field1, field2, field3 FROM table DESC";
$result = @mysql_query($query);
if ($result) {
$num = mysql_num_rows($result);
if ($num > 0) {
echo "Number of records = $num";
// Print the records
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
// do something with $row...
}
} else {
echo "No records found.";
}
}
Increment row count:
$query = "SELECT field1, field2, field3 FROM table DESC";
$result = @mysql_query($query);
$row_count = 0; // initialize
while ($row = mysql_fetch_row($result)) {
++$row_count;
// do something with $row...
} else {
$row_count = 0;
// do something with $row_count...
}
Some equivalents:
// (1) Get a result row as an enumerated array mysql_fetch_row($result) // is equivalent to mysql_fetch_array($result, MYSQL_NUM) // (2) Get a result row as an associative array mysql_fetch_assoc($result) // is equivalent to mysql_fetch_array($result, MYSQL_ASSOC)
Insert data into a table:
// Build the query
$query = "INSERT INTO table (field1, field2, field3)
VALUES ('$field1', '$field2', 'field3')";
// Run the query
@mysql_query ($query);
Functions
Truncate (shorten) a string to a set length:
// Declare and write the function
function truncate($string, $max = 100, $replacement = '') {
$startpos = $max - strlen($replacement);
return substr_replace($string, $replacement, $startpos);
}
// Usage (eg: shorten to 50 characters ending with '...'
if (strlen($string) > 49) {
$string = truncate($string, 50, '...');
}
With a just a few new images and a very minor change to the stylesheet, the pages can be given a completely different look...