Represent a PHP array as an encoded string

Sometimes we have a need to take a simple PHP array and represent it as an encoded string.

One use case that we have for this at DaniWeb is when a new user signs up, and we ask them to click on a link that was sent to them via email to verify their email address. The URL that they click on has, as a query string parameter, an encoded version of a PHP array that contains information such as the user's ID # and email address. This way, when the user clicks the link, we already know everything we need to about the user and can easily update that user's ID record, without their email address being in plain text in the URL that they click.

Basically what we're doing is converting the array to a JSON string that represents the array contents, then converting that string to a hexidecimal string, and then converting that base 16 string to a base 62 string to condense it (by utilizing A-Za-z0-9).

For example, suppose I have the following PHP array:

$array = array('foo', 'bar', 'baz', 'bat');

This function will convert that array to the simple string 43iGVuUpQisSlw7JnbQyrR8c2AtKX8lCiT.

This also works with associative arrays, multidimensional arrays, etc.

As a reminder, this does not one-way encrypt the string, and it's pretty easy to decode, because it just encodes the string, and doesn't encrypt it. Don't use this for passwords or for anything sensitive!

A good use case is, what we do, which is use it to transport complex data structures via a public-facing URL.