QRdvark Examples

Create Round Robin Using PHP

For those who have ever wanted to run a football league, or any sort of league requiring a round robin style of game draws, this simple function takes an array of team names (or numbers) and returns an array of the teams games. This function also takes into account byes when an odd number of teams is given.

Mod Rewrite Test Htaccess Is Installed And Working

Many PHP scripts, frameworks rely on the use of mod_rewrite for the application to correctly route requests. Often times, checking if there is a fault in the set up of the application, or, whether or not mod_rewrite is enabled or working can be confusing. This simple test will verify that mod_rewrite is correctly working, so that this error can be eliminated from the list of possible causes.

Trim All Members Of An Array With PHP

This little helper function provides a simple method to trim the white space from the beginning and end of all the elements in an array. It uses the call to array trim, which, in turn, calls the trim() function. The iteration is handled internally and so provides maximum performance then dealing with the the problem in user code.

Validate Date Using PHP

PHP provides many date manipulation devices and an entire suite of date functionality with the datetime class. However, this does not address date validation, that is, what format a date is received in. The PHP strtotime() function will accept many forms of dates in most human readable strings. The issue with strtotime is that there is no way to account for differing date formats, eg: 12/05/2010. Depending on what country a user is from, this date could have several meanings, such as which is the month, and which is day field. By splitting the date into its respective fields, each segment can be checked with the PHP checkdate function. The function below validates a date by splitting the date in year, month, day and using these as arguments to the checkdate function.

Convert Fixed Width To Array

Following on from a recent posting a request was recieved to convert a fixed width file into an array. The process is quite similar to creating a class as the file is iterated over and the array of positions and widths are used to build the array. In this example, the SplFileObject and SPL CachingIterator are used to traverse each line of the file, and then the fixedWidthToArray() function takes care of the business of creating an array of fields from each line.

Calculate Age With PHP

Checking dates in PHP can be problematic as PHP primarily concerns itself with date manipulation which revolves around unix timestamps. This is a good thing, mostly. Unix timestamps however, have not concept of leap years, thus it is difficult, though not impossible, to get an accurate date calculation from them. When dates need to be accurate for legal reasons, it is vital that the leap years are considered. Here several solutions are put forward, each nicer than the previous.

Read Line From File

Reading files in PHP can be a tricky business if not handled correctly. Most often when confronted with reading a line from, the nearest tool to hand is the file() function. The problem with using the file() function is that it reads the whole file into an array, and thus, into memory. Any subsequent operations on the array, such as foreach() result in an internal copy of the array for PHP to work on. Should the file be a two gig log file, then the result could be up to four gigs worth of memory being devoured to gain a few hundred k of text.

Set Checkbox With Xajax

Xajax brings speed and simplicity to creating ajax functionality from with PHP. An problem that often arises is assigning the value of a checkbox to checked. This can be used to either set a default checked option, or in relation to another event. Many times code arises trying to set the the checkbox to checked by assigning 'checked' or value='checked'. The key to producing the correct result is to remember how a checkbox is represented in the Document Object Model (DOM)

PHP Bullshit Meter

Have you ever sat in a boardroom, meeting, or had to wade through pages of specs only to find that a very small percentage of the information is actually useful, and the rest is utter bullshit. This simple function provides a method to measure exactly how much BS is contained in a string. The process is quite simple in that the length of the string is measured, and a percentage calculated from the total length of the BS in the bs array. Feel free to add you own bs words to the array.

Strip All Non Alphanumeric Characters Except Space With PHP

A quite common request received by QRdvark is to strip all "bad characters" except for a space. Bad characters are defined in these requests as any non alpha numeric characters. Most often these requests are from people who wish to sanitize postal addresses or the like. This simple function provides a basic wrapper for the PHP function preg_match to strip out the unwanted characters and returns a sanitized string, including white space characters.

Decode Utf8

Handling UTF-8 characters in PHP can be cumbersome. The PHP iconv and translit make a fair attempt at translating characters, but mostly the results are less than pleasing for the use of readability, or presentation. This little helper function simply takes two arrays and substitutes the values with a string replacement. Adding additional characters is simply a matter of adding to the arrays.

Get Vernal Equinox

Equinox: (Latin: Equal night) This example came about after a previous example to get the season for a given date. In the southern hemisphere, seasons are calculated simply by date. Summer down here begins on December first, Autumn on March first, Winter on June first, and Spring on September first. This works well, and the seasons can be adjusted simply to transpose them into values that correspond to the nothern hemisphere. But these dates do not truely reflect the beginning of spring in the northern hemisphere, or autumn in the southern hemisphere. Historically, in the northern hemisphere, the beginning of spring is marked by the spring, or Vernal, Equinox. The Vernal Equinox marks the point in time when the Sun crosses the celestial equator from south to north. Calculation of the true Vernal Equinox is regarded by some as the true beginning of spring, while some churches relate to it in a totally different way.

Calculate Installment Payment Regime

This PHP function calculates the number of installments required to pay a given amount. It will also calculate the last payment which is always lower than the regular installments. This PHP function can be useful when a payment plan such as lay-by/lay-away is required or just when Imran owes you money. The number of installements is the total number of installments including the last payment.

Get Links With DOM

Perhaps the biggest mistake people make when trying to get URLs or link text from a web page is trying to do it using regular expressions. The job can be done with regular expressions, however, there is a high overhead in having preg loop over the entire document many times. The correct way, and the faster, and infinitely cooler ways is to use DOM.

Get Season

The PHP date functions and datetime class provide many ways to gain and manipulate dates and times. However none of them address the four seasons. This example function will return the season based on the month and hemisphere.

Dynamic Date Time Dropdown List

Recently while designing a text only site for the visually impaired, a method of inputting dates and times was needed. Accessibility determined a simple dropouts menu to allow input was desirable, then later formatted, using PHP, into a usable timestamp for INSERTion into a database. It is reproduced here in the hope that others with accessibility issues will find it of value.

Create Favicon With Imagick

Here is an example that will take any image format supported by Image Magick (is there one that is not?) and create a 16 pixel favicon image from it. The cropThumbnailImage() method does the work of resizing and cropping in a single swoop while the setFormat() method converts the file to .ico format.

Thumbnail From Animated GIF

Seperating the individual images in an animated gif with PHP has never been easier than now with the Imagick extension. The Imagick extension allows a vast array of functionality with image manipulation. Here an animated gif is iterated over frame by frame and each frame is resized and thumbnailed. Note the use of writeImages() instead of writeImage(). A handy trick when needing to thumbnail an animated gif

Get Relative Root

PHP provides functions to get the webserver document root within the $_SERVER super global array, and for getting the current working directory with the getcwd() function. But it often occurs that the document is being served from another directory within the web tree. This function will get the current working directory, relative to the web server document root.

Substr In Array

To find if a value exists in an array, the PHP in_array() function works quite nicely. But there are times when only a partial match is required to check in the array. This substr_in_array() function checks will search the values of an array for a substring. The $needl can be a string or an array of strings to search for

Atomic Time

Here is a function to fetch the Atomic Time from an online atomic clock. When the right time is crucial in an application, and the time on the server clock cannot be trusted or is incorrect, this function will provide assurance the the time is correct.

Get Text Between Tags

QRdvark.com recieves many requests for solutions to every day problems. The most popular request is to find the text between two tags. These may be HTML body tags or XML tags or other. This function will get the text between tags of any named tag. This enables the user to specify any tag and the function will return the text inside.

Strip Single Tag

The PHP strip_tags function allows for the stripping of tags and excludes the ones to be maintained. This function allows the user to specify exactly which tags to be stripped, and all others are maintained. The option is available to strip a single HTML or XML tag also. Very handy if stripping of only a single, or more tags is required.

Month Dropdown List

Here is a function to create an HTML dropdown list of months. Handy for use in form classes or any script where you need to display a dropdown month list like a calander class. Two options are provided for this function, demonstrating different approaches and different speeds.

Recursive In Array

Recursively search a multi-dimensional array for any occurrance of a string. This function works in the same way as the PHP function in_array except this function works on single dimensional or multi-dimensional arrays. An option is also provided to check for type.

Convert Seconds To Words

This function takes a UNIX TIMESTAMP as generated by strtotime or from any source and converts it into a human readable notation. Convert seconds to words is a function that should be done at the application level and not from from SQL queries as this may interfere with display logic.

Radians To Degrees

This function complements the Degrees to Radians functions by doing exactly the opposite, converting radians to degrees. Handy for those geographical calculations need when plotting points on a map with with online applications such as google maps or yahoo maps.

US Cities Zip Codes

Ever needed a comprehensive list of US cities, zip codes, latitude and longitude? Well you can pay up to $100 dollars for one or you can use this database of over forty one thousand (41000) cities and their locations. Great for geo targetting and geo location in your next application.

58000 Words

58000 Words is a MySQL table containing just what it says, over 58000 words in a MySQL dump so you can stick it directly into your database for use in your applications. Great for any time you need a word list to match against.