Sometimes UNIX timestamps can be easier to manage than MySQL datetimes. Here’s a function from converting one to the other.
get_distinct_size_2_subsets()
This function should REALLY come in handy for a lot of folks (heavy sarcasm). It calculates all size 2 subsets of an array whose values are unique, and in no particular order. So, passing it an array of [1,2,3] will return [[1,2],[1,3],[2,3]]. Passing it an array of [1,2,3,2,1,2,3] will return exactly the same thing. Go wild!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | function get_distinct_size_2_subsets($array) { $subsets = array(); // if the array only contains two or less element, just return it if (count($array) <= 2) return $array; for ($i=0; $i<count($array); $i++) { $curr_el1 = $array[$i]; for ($j=0; $j<count($array); $j++) { $curr_el2 = $array[$j]; if ($curr_el1 == $curr_el2) continue; // if an element of [$curr_el1, $curr_el2] and [$curr_el2, $curr_el1] doesn't exist, // add if to $subsets if (!in_array(array($curr_el1, $curr_el2), $subsets) && !in_array(array($curr_el2, $curr_el1), $subsets)) $subsets[] = array($curr_el1, $curr_el2); } } return $subsets; } |
function: cleanPhoneString()
A function written by Julius Davies, an old friend of mine who’s actually responsible for getting me into programming in the first place. He’s posted a demonstration of this function on his site, here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | /* Takes a string (hopefully containing digits), strips out all garbage, and returns it as a nicely formatted phone number. cleanPhoneString("6042513219") returns: "604-251-3219" cleanPhoneString("60425132191234") returns: "604-251-3219 x 1234" cleanPhoneString("6a0b4c2d5e1f3g2h1i9") returns: "604-251-3219" This method is meant to be used hand-in-hand with "isValidPhoneString()". Example usage: $cleanPhone = cleanPhoneString( $str ); if ( !isValidPhoneString( $cleanPhone ) ) { $cleanPhone = "invalid!"; } */ function cleanPhoneString( $phoneStr ) { $len = strlen( $phoneStr ); $buf = ""; for ( $i = 0; $i < $len; $i++ ) { $c = $phoneStr{$i}; if ( ctype_digit( $c ) ) { $buf = $buf.$c; } } $phoneStr = $buf; $len = strlen( $phoneStr ); $buf = ""; for ( $i = 0; $i < $len; $i++ ) { $c = $phoneStr{$i}; if ( ctype_digit( $c ) ) { if ( $i == 3 || $i == 6 ) { $buf = $buf."-"; } else if ( $i == 10 ) { $buf = $buf." x "; } $buf = $buf.$c; } } return $buf; } /* Tests to make sure string is a valid phone number. You should first run your string through cleanPhoneString() first, since isValidPhoneString() depends on the formatting provided by cleanPhoneString(). */ function isValidPhoneString( $phoneStr ) { $l = strlen( $phoneStr ); $c = ""; if ( $l >= 1 ) { $c = $phoneStr{0}; } // Must be at least 12 digits (xxx-xxx-xxxx), and must // not start with 0 or 1. Must not be more than 20 digits // (xxx-xxx-xxxx x xxxxx). return $l >= 12 && $l <= 20 && $c != '0' && $c != '1'; } |
Removing index from array
I can’t believe PHP doesn’t have a built-in function for this…! Code snippet for removing a single index from an array (non-associative).
1 |
Function: check_upload_folder()
A catch-all function to check that a folder is able to handle file uploads. In addition to the standard check that the folder specified exists, is readable and is writable, it also checks your server’s PHP installation to confirm that the temporary upload folder is in fact valid. Up until this point I’ve always naively assumed that the smart folks who set up servers know to configure that value properly. But a couple of chaps on the Form Tools forums found that their installations of PHP had invalid settings – or weren’t set at all. Doh!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | /*------------------------------------------------------------------------------------------------*\ Function: check_upload_folder Description: examines a folder to check (a) it exists and (b) it has correct permissions. This function also checks to see if the upload_temp_dir server setting has been configured. Parameter: the full path to the folder to be examined. \*------------------------------------------------------------------------------------------------*/ function check_upload_folder($folder) { // first, check server's temporary file upload folder $upload_tmp_dir = ini_get("upload_tmp_dir"); if (empty($upload_tmp_dir)) return array(false, "Your server's installation of PHP doesn't appear to have the <b>upload_tmp_dir</b> setting configured. This setting determines where files are temporarily uploaded to before they are moved to the folder you are specifying here. This value needs to be set in order to allow this program to properly upload files. Please contact your hosting provider."); if (!is_dir($folder)) return array(false, "Your server's installation of PHP has an invalid setting for the <b>upload_tmp_dir</b> value. \"$upload_tmp_dir\" is not a valid folder."); if (!is_writable($folder)) return array(false, "This temporary upload folder specified by your PHP installation is not writable. Until this is fixed, files cannot be uploaded through any PHP program on your server. Please contact your hosting provider."); // now check the folder specified by if (!is_dir($folder)) return array(false, "This is not a valid folder."); if (!is_writable($folder)) return array(false, "This folder is not writeable."); return array(true, "This folder has the correct permissions."); } |
Function: get_date()
Helpful wrapper function used in my Form Tools script for converting a MySQL datetime into a human readable format. Includes the option of specifying hour offset. It gets pretty annoying having to rethink this problem every time you need it, so here it is for reference.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | /*-----------------------------------------------------------------------------------------*\ Function: get_date Description: helper function to return a date according based on an offset and a display format. Parameters: $offset - the GMT offset $datetime - the mysql datetime to format $format - the format to use (PHP's date() function). \*-----------------------------------------------------------------------------------------*/ function get_date($offset, $datetime, $format) { $year = substr($datetime,0,4); $mon = substr($datetime,5,2); $day = substr($datetime,8,2); $hour = substr($datetime,11,2); $min = substr($datetime,14,2); $sec = substr($datetime,17,2); return date($format, mktime($hour + $offset, $min, $sec, $mon, $day, $year)); } |
Function: generate_random_alphanumeric_str()
Another function, used in my Data Generator. This function accepts a single string as an argument, which may contain characters with pre-set meaning (see doc below). They are converted to their appropriate meaning and the entire string is returned.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | /*------------------------------------------------------------------------*\ Function: generate_random_alphanumeric_str Purpose: converts the following characters in the string and returns it: C, c, A - any consonant (upper case, lower case, any) V, v, B - any vowel (upper case, lower case, any) L, l, V - any letter (upper case, lower case, any) X - 1-9 x - 0-9 \*------------------------------------------------------------------------*/ function generate_random_alphanumeric_str($str) { $letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $consonants = "BCDFGHJKLMNPQRSTVWXYZ"; $vowels = "AEIOU"; $new_str = ""; for ($i=0; $i<strlen($str); $i++) { switch ($str[$i]) { // Numbers case "X": $new_str .= rand(1,9); break; case "x": $new_str .= rand(0,9); break; // Letters case "L": $new_str .= $letters[rand(0, strlen($letters)-1)]; break; case "l": $new_str .= strtolower($letters[rand(0, strlen($letters)-1)]); break; case "D": $bool = rand()&1; if ($bool) $new_str .= $letters[rand(0, strlen($letters)-1)]; else $new_str .= strtolower($letters[rand(0, strlen($letters)-1)]); break; // Consonants case "C": $new_str .= $consonants[rand(0, strlen($consonants)-1)]; break; case "c": $new_str .= strtolower($consonants[rand(0, strlen($consonants)-1)]); break; case "E": $bool = rand()&1; if ($bool) $new_str .= $consonants[rand(0, strlen($consonants)-1)]; else $new_str .= strtolower($consonants[rand(0, strlen($consonants)-1)]); break; // Vowels case "V": $new_str .= $vowels[rand(0, strlen($vowels)-1)]; break; case "v": $new_str .= strtolower($vowels[rand(0, strlen($vowels)-1)]); break; case "F": $bool = rand()&1; if ($bool) $new_str .= $vowels[rand(0, strlen($vowels)-1)]; else $new_str .= strtolower($vowels[rand(0, strlen($vowels)-1)]); break; default: $new_str .= $str[$i]; break; } } return trim($new_str); } |
Function: get_random_subset()
Simple helper function which returns a random subset of an array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | /*-------------------------------------------------------------------------------------*\ Function: get_random_subset Description: accepts an array as an argument, and returns a random subset of its elements. May be empty, or the same set. Parameters: $set - the set of items $num - the number of items in the set to return \*-------------------------------------------------------------------------------------*/ function get_random_subset($set, $num) { // check $num is no greater than the total set if ($num > count($set)) $num = count($set); shuffle($set); return array_slice($set, 0, $num); } |
Function: get_thumb_dimensions()
This is an old function I wrote a bazillion years ago for calculating the dimensions of an image (aspect-ratio-preserved) that would fit within a fixed-size box (specified by $max_width, $max_height). Still useful.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | /*----------------------------------------------------------------------------*\ Function: get_thumb_dimensions Description: examines an image and calculates thumbnail dimensions for it, based on the max width and height dimensions passed in as parameters. Returns an array containing the width [0] and height [1] Parameters: $image - the image name and path $max_width - the max width of the thumbnail $max_height - the max height of the thumbnail \*----------------------------------------------------------------------------*/ function get_thumb_dimensions($image_path, $max_width, $max_height) { // find the images dimensions $image_dimensions = getImageSize($image_path); $image_width = $image_dimensions[0]; $image_height = $image_dimensions[1]; // default the thumbnail dimensions to the maximum values $thumb_height = $max_height; $thumb_width = $max_width; // assume image width >= height $scaling_ratio = $image_width / $max_width; // compare the scaled height with the maximum thumb height. If it's bigger, // we need to find a new scaling ratio if (($image_height / $scaling_ratio) > $max_height) { $scaling_ratio = $image_height / $max_height; $thumb_width = $image_width / (float) $scaling_ratio; } else $thumb_height = $image_height / (float) $scaling_ratio; // now return the dimensions $thumb_dimensions = array($thumb_width, $thumb_height); return $thumb_dimensions; } |
Function: generate_password()
Simple helper function to generate a password for use in, say, a user account. Saves people the fuss and bother of coming up with their own. Takes a single parameter to determine the length of the password. Defaults to 8 chars.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | /*--------------------------------------------------------------------------*\ Function: generate_password Parameters: length - any integer value, specifying the length of the password. Returns: the password. Duh. \*--------------------------------------------------------------------------*/ function generate_password($length = 8) { $password = ""; $possible = "0123456789bcdfghjkmnpqrstvwxyz"; $i=0; // add random characters to $password until $length is reached while ($i < $length) { // pick a random character from the possible ones $char = substr($possible, mt_rand(0, strlen($possible)-1), 1); // we don't want this character if it's already in the password if (!strstr($password, $char)) { $password .= $char; $i++; } } return $password; } |
Recent Comments