Getting the Current Date and Time
Formatting Timestamps
Checking Date Validity
Converting Strings to Timestamps
Checking for Leap Years
// function to test if leap year function testLeapYear($year) { $ret = (($year%400 == 0) || ($year%4 == 0 && $year%100 != 0)) ∝ ? true : false; return $ret; } // result: "Is a leap year" echo testLeapYear(2004) ? "Is a leap year" : "Is not a leap year"; // result: "Is not a leap year" echo testLeapYear(2001) ? "Is a leap year" : "Is not a leap year"; ?>
Finding the Number of Days in a Month
Finding the Day-in-Year or Week-in-Year Number for a Date
Finding the Day Name for a Date
Finding the Number of Days or Weeks in a Year
// get total number of weeks in the year 2001 $numWeeks = date("W", mktime(0,0,0,12,28,2001)); // result: "There are 365 days and 52 weeks in 2001." echo "There are $numDays days and $numWeeks weeks in 2001.\n"; ?>
Finding the Year Quarter for a Date
Converting Local Time to GMT
Converting Between Different Time Zones
Converting Between PHP
and MySQL Date Formats tsField)); ?> tsField); ?>
To convert a UNIX timestamp to MySQL’s TIMESTAMP/DATETIME format, use the date() function with a custom format strong, or use MySQL’s FROM_ UNIXTIME() function: tsField; ?>
Comparing Dates
// compare timestamps // to see which represents an earlier date if ($date1 > $date2) { $str = date ("d-M-Y H:i:s", $date2) . " comes before " .∝ date ("d-M-Y H:i:s", $date1); } else if ($date2 > $date1) { $str = date ("d-M-Y H:i:s", $date1) . " comes before " .∝ date ("d-M-Y H:i:s", $date2); } else { $str = "Dates are equal"; } // result: "01-Feb-2007 00:00:00 comes before 01-Feb-2007 01:00:00" echo $str; ?>
Performing Date Arithmetic
Displaying a Monthly Calendar build(); // format as table echo "
"; // print month and year on first line echo " " . sprintf("%02d", $month->thisMonth()) . "/" .∝ $month->thisYear() . "\n"; // print day names on second line echo " M T W T F S S\n"; // iterate over day collection while ($day = $month->fetch()) { if ($day->isEmpty()) { echo " "; } else { echo sprintf("%3d", $day->thisDay()) . " "; } if ($day->isLast()) { echo "\n";
} } echo "
"; ?>
Working with Extreme Date Values
Printing Arrays array( "longname" => "United Kingdom", "currency" => "GBP"), "US" => array( "longname" => "United States of America", "currency" => "USD"), "IN" => array( "longname" => "India", "currency" => "INR")); // print array contents print_r($data); var_dump($data); ?>
∝
Processing Arrays "London", "US" => "Washington",∝ "FR" => "Paris", "IN" => "Delhi"); // process and print array elements one by one // result: "UK: London US: Washington FR: Paris IN: Delhi " foreach ($assocArr as $key=>$value) { print "$key: $value"; print "
"; } ?>
Processing Nested Arrays
Counting the Number of Elements in an Array
Converting Strings to Arrays
Swapping Array Keys and Values "black", "day" => "night", "open" => "close"); // exchange keys and values // returns ("black" => "white", "night" => "day", "close" => "open") print_r(array_flip($opposites)); ?>
Adding and Removing Array Elements
Use PHP’s array_splice() function to add or remove elements from the middle of an array:
Extracting Contiguous Segments of an Array
Removing Duplicate Array Elements
Re-indexing Arrays "spiderman", 1 => "superman",∝ 2 => "captain marvel", 3 => "green lantern"); // remove an element from the middle of the array // result: (0 => "spiderman", 1 => "superman", 3 => "green lantern") unset ($superheroes[2]); // rearrange array elements to remove gap // result: (0 => "spiderman", 1 => "superman", 2 => "green lantern") $superheroes = array_values($superheroes array_values($superheroes); ); print_r($superheroes); ?>
Randomizing Arrays
Reversing Arrays
Searching Arrays "United Kingdom", "US" => "United States of America", "IN" => "India", "AU" => "Australia"); // search for key // result: "Key exists" echo array_key_exists("UK", $data) ? "Key exists" : "Key does not exist";
∝
// search for value // result: "Value exists" echo in_array("Australia", $data) ? "Value exists" : "Value does not exist"; ?>
∝
Searching Nested Arrays $value) { if (preg_match("/$needle/i", $key)) { $matches[] = array($path . "$key/", "KEY: $key"); } if (is_array($value)) { // if a nested array // recursively search // unset the path once the end of the tree is reached $path .= "$key/"; arraySearchRecursive($needle, arraySearchRecursive($need le, $value, $path); unset($path); } else { // if not an array // check for match // save path if match exists if (preg_match("/$needle/i", $value)) { $matches[] = array($path . "$key/", "VALUE: $value"); } } } // return the list of matches to the caller return $matches; } // define nested array $data = array ( "United States" => array ( "Texas", "Philadelphia", "California" => array ( "Los Angeles", "San Francisco" => array( "Silicon Valley")))); // search for string "in" // result: an array of 2 occurrences with path print_r(arraySearchRecursive("co", print_r(arraySearchRecursi ve("co", $data)); ?>
Filtering Array Elements 0) ? true : false; } // define array of numbers $series = array(-10,21,43,-6,5,1,84, array(-10,21,43,-6,5,1,84,1,-32); 1,-32); // filter out positive values // result: (21, 43, 5, 1, 84, 1) print_r(array_filter($series, print_r(array_filter($seri es, 'isPositive'));
?>
Sorting Arrays
Sorting Multidimensional Arrays "Net Force", "author" => "Clancy, Tom", ∝ "rating" => 4); $data[1] = array("title" => "Every Dead Thing", "author" => "Connolly, ∝ John", "rating"=> 5); $data[2] = array("title" => "Driven To Extremes", "author" => "Allen, ∝ James", "rating" => 4); $data[3] = array("title" => "Dark Hollow", "author" => "Connolly, ∝ John", "rating" => 4); $data[4] = array("title" => "Bombay Ice", "author" => "Forbes, ∝ Leslie", "rating" => 5); // separate all the elements with the same key // into individual arrays foreach ($data as $key=>$value) { $author[$key] = $value['author']; $title[$key] = $value['title']; $rating[$key] = $value['rating']; } // sort by rating and then author array_multisort($rating, $author, $data); print_r($data); ?>
Sorting Arrays Using a Custom Sort Function strlen($b)) ? 1 : -1; } }
} // define array $data = array("abracadabra", "goo", "indefinitely",∝ "hail to the chief", "aloha"); // sort array using custom sorting function // result: ("goo", "aloha", ..., "hail to the chief") usort($data, 'sortByLength'); print_r($data); ?>
Sorting Nested Arrays strlen($b)) ? 1 : -1; } } } // function to recursively sort // a series of nested arrays function sortRecursive(&$arr, $sortFunc, $sortFuncParams = null) { // check if input is array if (!is_array($arr)) { die ("Argument is not array!"); } // sort the array using the named function $sortFunc($arr, $sortFuncParams); // check to see if further arrays exist // recurse if so foreach (array_keys($arr) as $k) { if (is_array($arr[$k])) { sortRecursive($arr[$k], $sortFunc, $sortFuncParams); } } } // define nested array $data = array ( "United States" => array ( "West Virginia", "Texas" => array( "Dallas", "Austin"), "Philadelphia", "Vermont", "Kentucky", "California" => array ( "San Francisco", "Los Angeles", "Cupertino", "Mountain View"))); // sort $data recursively using asort() sortRecursive($data, 'asort'); print_r($data); // sort $data recursively using custom function() sortRecursive($data, 'usort', 'sortByLength'); print_r($data); ?>
Merging Arrays
"apple", "b" => $ac = array("a" => "anteater", "c" $bcd = array("b" => "ball", "c" => "d" => "demon"); // recursively merge into a single $abcd = array_merge_recursive($ab, print_r($abcd); ?>
"baby"); => "cauliflower"); array("car", "caterpillar"),∝ array $ac, $bcd);
Comparing Arrays
Use PHP’s array_diff() function to find the elements that exist in either one of the two arrays, but not both simultaneously:
Controlling String Case
Checking for Empty String Values
?>
Removing Characters from the Ends of a String
Removing Whitespace from Strings
Reversing Strings
Repeating Strings
Truncating Strings $maxChars) { return trim(substr($str, 0, $maxChars)) . $holder; } else { return $str; } } // define long string $str = "Just as there are different flavors of client-side scripting,∝ there are different languages that can be used on the server as well."; // truncate and print string // result: "Just as there are different flavours of..." echo truncateString($str); // truncate and print string // result: "Just as there are di >>>" echo truncateString($str, 20, " >>>"); ?>
Splitting Strings into Smaller Chunks
Comparing Strings for Similarity
similar" == metaphone("reset")) ? ∝ "Strings are not similar"; similar" == metaphone("dip")) ? ∝ "Strings are not similar"; not similar" == metaphone("higher")) ? ∝ "Strings are not similar";
Parsing Comma-Separated Lists
Parsing URLs $v) { echo "$k: $v \n"; } ?>
∝
Counting Words in a String
Spell-Checking Words in a String
$words = preg_split('/[^0-9A-Za-z\']+/', $str, -1, ∝ PREG_SPLIT_NO_EMPTY); foreach ($words as $w) { if (!pspell_check($dict, $w)) { $errors[] = $w; } } // if errors exist // print error list if (sizeof($errors) > 0) { echo "The following words were wrongly spelt: " . ∝ implode(" ", $errors); } ?>
Identifying Duplicate Words in a String $v) { if ($v >= 2) { print "$k \r\n"; } } ?>
Searching Strings tired and so I
must go
home now"; // check for match // result: "Match" echo ereg("
(.*)+", $html) ? "Match" : "No match"; ?>
Use a regular expression with PHP’s preg_match() function: tired and so I
must go
home now"; // check for match // result: "Match" echo preg_match("/
(.*?)<\/b>/i", $html) ? "Match" : "No match"; ?>
Counting Matches in a String tired and so I
must go
home now"; // count occurrences of bold text in string // result: "2 occurrence(s)" preg_match_all("/
(.*?)<\/b>/i", preg_match_all("/(.*?)< \/b>/i", $html, &$matches); echo sizeof($matches[0]) . " occurrence(s)"; ?>