Useful PHP Snippets

Sometimes little bits of PHP can make your life easier. The following are a few helpful little bits of code you can use in your webpages.

Add an ordinal to the end of a number

I’ve seen several of these and some are more elegant than others.  This isn’t one of the most elegant in my opinion, though it is a function.

Here’s one that I think is better. Note that it doesn’t have brackets in statements.

Serialization

Sometimes you need to convert your arrays or objects into formatted strings so that you can do other things with the data. This comes from the article 9 Useful PHP Functions and Features You Need to Know.

There are two popular methods of serializing variables. Here is an example that uses the serialize() and unserialize():

This was the native PHP serialization method. However, since JSON has become so popular in recent years, they decided to add support for it in PHP 5.2. Now you can use the json_encode() and json_decode() functions as well:

It is more compact, and best of all, compatible with javascript and many other languages. However, for complex objects, some information may be lost.

Generating Unique ID’s

Often there are situations where you need to generate a unique string. People frequently use the md5() function for this, even though it’s not exactly meant for this purpose. This comes from the article 9 Useful PHP Functions and Features You Need to Know.

There is a PHP function named uniqid() that is meant to be used for this.

Even though the strings are unique, they seem similar for the first several characters. This is because the generated string is related to the server time. This has a nice benefit, as every new generated id comes later in alphabetical order, so they can be sorted.

To reduce the chances of getting a duplicate, you can pass a prefix, or the second parameter to increase entropy.