Test For Prime Numbers With PHP Regular Expression
This function provides a novel method of testing if a number is prime, by using a PHP regular expression.
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 Object To Array With PHP
Converting an object to an array using PHP comes with a small gotcha. One would be forgiven for thinking it is merely a task of casting the object and the job can be completed with a single line of code. This works well for simple objects, however, the task increases in complexity in line with the objects complexity.
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.
Image To Ascii Art With PHP
This PHP function creates a simple ascii art rendering of a jpg image. It uses GD to do the grunt work and some simple bit shifting to allocate shades. Colors are then moved into hex values and the text generated for output to the browser. Ascii art from an image with PHP is now easy.
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 PHPRO 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.
Create Halo Effect With Imagick
This simple example uses the imagick extension to create text on an image with halo or glow effect. The effect is quite simple to create by annotating in-focus text over blurred text. This can be used to create dynamic images with text for many uses.
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.
Calculate Friday The 13th With Datetime Class
Calculating the dates of Friday the 13th for the next n years is not a difficult task. But it does provide the opportunity to flex the muscles of the PHP DateTime class to overcome some of the limitations of unix timestamps.
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 Amounts
This function is the anitithesis of the Calculate Installment Payment Regime. This function will calulate the installment payment amounts for an amount, given the amount and the number of installments to make. This function will also calculate and return the amount of the final installment, which is always slightly lower than the regular installment amounts.
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.
Variable Number Of Arguments
If you need to pass arguements to a function, but the number of arguements is variable, then an array looks the only choice. However, PHP allows functions to take a variable number of arguements to any user defined function.
Easter Egg
The life of a PHP core developers can be unsatisfying. Constantly striving to fit in many hours of unpaid development to bring the world a better product. It is little wonder that sometimes, a mischivious deed breaks the tediom. Easter Eggs are nothng new in programming, and PHP joins the rest with own version.
GD Thumbnail Based On Image Type
This example is an extension of the Create Thumbnail With GD example from earlier. This example provides auto detection of image type, resizing with aspect ratio, and variables for control of thumbnail size and quality. A great start to writing your own image gallery or anywhere you need ana image thumbnail.
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.
Array Sum Recursive
This simple function is a compliment to the PHP array_sum() function with the difference this function will handle multi-dimensional arrays of any depth.
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.
Format Date For RSS Feed
Here is a small, but useful function that will format a date for use in RSS feeds. The publication date, or pubDate for RSS feeds is optional but it is a handy addition for RSS feeds that are updated often.
Convert Seconds To Hours Minutes Seconds Words
This function will convert a number of seconds into words expressing hours, minutes and seconds. Great for those times when a more verbose reading is required
Create Thumbnail With GD
The GD graphics library that is bundled with PHP provides many functions to enable image manipulation from within PHP. The most commonly requested task is thumbnailing images. This script shows a simple method to use GD to thumbnail an image and save it to disc.
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
PHP Errors As Exceptions
PHP contains a robust feature set of error handling mechanisms such as E_WARNING, E_STRICT, E_ALL etc. Often these errors pop up unexpectedly at run time and should be handled correctly. This function provides a method of handling runtime errors as exceptions.
Get Text Between Tags
PHPRO.ORG 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.
Recursive File Exists
The PHP file_exists() function provides a method of checking if a file exists at a given path. This function extends this functionality to check if a file exists anywhere within a provided directory recursively. This means the file may be within any sub directory also and still be found.
Ordinal Suffix
This function will append the ordinal suffix to a number. If you need this for dates, the PHP date() function has an option for this. For all other times you need to supply add st, nd, rd, th.
All UK Counties
Recently, a PHPRO.ORG user requested a database of all the Counties in the UK. Not towns or cities, just the Counties. This database dump provides a table of all Counties in the UK. Ideal for dropdown menus or any other use.
PHP Finger Client Linux Kernel
This example shows how to create a simple finger client with php. The script connects to kernel.org to fetch the latest linux kernel information. Here a simple unordered list is created to display the contents. Handy for displaying the latest kernel updates on you website
Unicode Chart
Ever needed to generate a unicode table? Me either, but a PHPRO.ORG visitor asked how it might be done, here is one of a many possibilities
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
Convert Numbers To Roman Numerals
Roman numerals can add a bit of pizzaz to a site or be used in legal documents or even for giving a site a touch of gladitorial grace. This function will convert a number to a roman numeral that can be used anywhere on a site.'
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.
Rainbow Text
A litte helper function to make your site emo2.0 compliant. This site will convert text into rainbow text. The text is colored in various colors to give swirling colored effect if used in long text strings.
Find Position Of Nth Occurrence Of String
The PHP functions that search strings do a fine job of finding the first of last occurance of a search string. But what if the task was to find the second or third occuance of a string within a string. This function provides an offset parameter to find the Nth occurance of a string within a string.
Get Domain Name From URL
This function will extract the domain name from a URL. The url can be any valid URL containg the scheme and hostname. The function will discard other information and return only the http://www.phpro.org portion of the URL string.
Alternating Row Colors
Displaying tabular data from arrays and database results often make use of a table with alternating row colors. This simple example shows how alternating row colors can be used to make every second table row a different color.
Google Maps With PHP And Phproogle
The PHPRO phproogle class allows PHP developers to quickly create Google Maps without needing to bother with the mind boggling Google Maps API. This class allows developers to create a Google Map using on PHP and the phproogle class will take care of the rest
Recursively Rename All Files In Directory With RecursiveDirectoryIterator
The PHP SPL Iterators are used in this function to efficiently recurse through a directory and rename the files within. By using the RecursiveDirectoryIterator and the RecursiveIteratorIterator the recursion is done by PHP and there is no need to be writing recursive functions within the code base.
Convert Photoshop PSD File With Imagick
Sometimes a user needs up upload a photoshop PSD file to a site. With the PHP Imagick extension the power of ImageMagick can be employed to convert the photoshop PSD file into a JPG, PNG or any other image format supported by ImageMagick.
Parse HTML With PHP And DOM
For many, the process of parsing varibles out of HTML tables has been a hard grind with numerous regular expressions and string functions. This example code shows how to parse HTML with PHP using the DOM extension to gain the values of data stored within the HTML table.
First Day Of Month
The first day of the month function does exactly as you would expect, it fetches the first day of the month. The default behavior is to default to the current month, but an optional parameter allows for fetching of the first day of any month, any time.
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.
Days Of Week Dropdown
A dropdown menu list for use in forms or calander class or wherever days of the week are required. The days and numbers have been assigned as per ISO-8601 to give the greatest compatibility with other calendar systems.
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.
Days Between Two Dates
This function provides a simple and effective method of counting the number of days between two dates. An option is also provided to return partial days also. This function does not calculate years or months or seconds, only days. Ideal for countdown scripts and the like.
Validate Email By Regular Expression
Latter day PHP versions have the benifit of validating email address using the filter_var function from the filter extension. For those who dont have access to filter var, or simply prefer to do things with a regular expression, this function will validate most email addresses using a simple regular expression.
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.
Create Columns From Array
Creating columns from an array or from a database result set can seem a little tricky. The key to making it happen is the PHP modulo operator. With some simple math, database result sets and arrays can be rendered in two, three, four or more columns.
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.
Create-Test-Database
Here is a small but useful script to create test data for databases. Two test tables are created with PDO and filled with various data types including Binary (BLOB) data.
80000 Word List
Some times you just need a list of words, a big list. Here is a list of about eighty thousand words to help with.. well whatever!
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.
Degrees To Radians
Here is a handy function for those messing with goe location and geo targetting or other geo graphical toys. This function convert degrees to radians for use in map plotting etc.
Get Riemann Distance
This function will calculate the distance between two points on the earth using the great circle distance formulae. This function should not be used to calculate linear distances, instead use the GetLinearDistance function. This function will return a value in miles, nautical miles or kilometers
Get Linear Distance
This function calculates the linear distance between two points. Give to x1 y1 x2 and y2. This is not a function for calculating distances between latitudes and longitutes, for that purpose see the Get Riemann Distance function.
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.
Get Full URL
A PHP function to get the full url of a web page. This function gathers several of the PHP super globals to create the whole URL.
Get Link Text
Ever wanted to get the text component of a URL. Not the link destination but the link itself. Well you search is over because the work has been done for you.
Calculate How Many Years Old
This function will work out how many years old you are based on a date provided in any format that is readable by strtotime. The function itself returns an integer of how many year old minus months day etc.
Convert BMP to JPG
The PHP GD library lacks the ability to convert BMP images to JPG. This can be achieved with the Imagick extension but for those folks with only GD at their disposal, this function will get you through the day.
Convert Unix Timestamp To MySQL Timestamp
Here is a quick but useful function to convert PHP time to MySQL times. That is, UNIX TIMESTAMP to MySQL TIMESTAMP format. Handy for all those times you need to deal with changing date formats.
Create Horizontal Gradient With PHP Imagick
The PHP Imagick extension allows for the creation of gradients. By default these gradients are vertical. This example code provides a method of creating horizontal gradients using simple rotation.
Password Strength Tester
PHP Security is an important part of creating forms. Recently there has been a proliferation of password strength testing scripts about, each with their own algorithms for checking the strength of passwords. This example shows how it is done.
Twenty Four Hour to Twelve Hour
Converting 24 hour time to 12 hour can be a hassle when you have different formats. This helper function takes 24 hour times and converts them to its 12 hour counterpart. Fun for all ages.
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.
Directory-Size
When you need to get the size of an entire directory using PHP this function will give you result in Bytes. You can then do the math to format it into KB or MB or whatever format you like.',
PDO to Array
Here is a small utility function that takes the result of a PDO query using a key value pair and creates a single dimensional array from it.
Imagick Thumbnail From Center
This thumbnailer script is a little different from many by allowing the user to crop from the center of an image instead of the everyday resizing that pollutes the net
PHP Xajax Loading Message
This example shows how to use PHP and Xajax to create a Loading message while a server task is being processed. Handy for those occasions when you do not need a progress bar. More on the progress bar later.
PHP Xajax Accordian
This PHP Xajax script builds on the PHP Xajax Sliding Draw example and creates a great effect without any more knowledge of javascript than your socks.
PHP Xajax Sliding Draw
Ever needed a naf slideout draw to show and hide content but did not know enough javascript to get past hello world? me either, but with a little Xajax and PHP the job is little more than a chore.
Change Style with Xajax and PHP
For those new to xajax and PHP, here is a simple script to get you started. It shows how to change a divs style and content using xajax to call a PHP function.
Get All URLs From Page
I needed to get all the urls from a string. So I came up with this little function to do that. It will also get all the urls from a web page if you so desire.
wordbreak
Here is a useful PHP script that breaks a string at the last whole word before a specified number of characters. Great for news snippets or forums where you have a read more link etc.
Insert At Array Index
Here is a little helper function if you need to insert an array at a given index. Very useful when creating stuctured data for use in XML or CSV files, or any structure.
Flatten Array
This little helper is just what you need to flatten a multidensional array into a single level.
Count Lines in File
Often times we need to count the number of lines in a file. There is a right way and wrong way of achieving this goal. This is one of the right ways.
Array Values Similar
When the time comes that you need to be sure all the values of an array are identical, this little function will get you on the way.
Sanitize Email
As the internet expands, so do the amount of contact forms. Quite often these contact forms are exploited by spammers to send out millions of mails every year. Here we see how to make sure your contact form is not one of them.
First Words
Here is a NAF script to grab the first n number of words in a string. The number of words is variable to suit you application.
Lower Case an Array
Ever needed to change the case of all the elements in an array? This function shows how it is done.
Format Date
As a request to a phPro user, this function was created to format a UNIX timestamp with the default value as the current timestamp, then set the default timezone also.
Country Array
This handy array provides a list of country names and thier two letter country code as the array keys. Keep this one bookmarked.
Array Push Assoc
Random Password Generation
Convert Numbers to Words
Variable Variables
Write Text To Image
URL to Link
Variable number of arguements
Re-index Array
Text to Image with GD
PHP Tag Cloud
Push element onto the beginning of an array
Percentage match strings with PHP
PHP SERVER SUPER GLOBAL
Parse Camel Case
Parse Domain
List all variables
Multiple file upload
Generate Bar Graph with PHP and GD
Get File Extension
Delete Line From File
Example of destructor
Cut a deck of cards with PHP
Encode Email
Convert tai64 to timestamp
Create Anagrams
Convert Seconds to Numbers
Collapse Whitespace
Combine two arrays
Benchmark or time script
Check if number is Odd or Even
Abstract-Class-Example
Apache Log Date
RSS Feed
Search
PHPRO.ORG Poll
Warning: Participation in PHPRO.ORG polls may incorrectly lead you to believe your opinions matter.






