Converting Numeric Data to Alphanumeric in PHP with base_convert

Published: January 25, 2018

Tags:

Recently a client came to me with the following request…

We’re planning publish “offer codes” in our print circulars so that customers can search for more details on our website. The offer codes our system generates are long and will be cumbersome for users to enter into the search field on the website. What can we do about this?

The offer codes looked something like this…

I thought about it a little and then a lightbulb went off in my head :bulb:

This could be solved by stripping the “PRE-“ (which was consistent across every offer code) and converting the remaining numeric data to alphanumeric via a base-10 to base-36 conversion. The result would be short alphanumeric codes that looked something like this…

In this post we’ll look at how this can be achieved in PHP.

The Implementation

Converting from numeric to alphanumeric is very easy in PHP. The base_convert function is designed to do exactly this.

Here’s the signature for the function…

string base_convert( string $number, int $frombase , int $tobase )

base_convert allows for conversion beginning from base-2 (binary) all the way to base-36 (alphanumeric).

This is what the implementation looked like for me…

$offerId = 'PRE-0019003400';
$alphanumeric = base_convert($offerId, 10, 36);

A couple things worth noting…

Max Chadwick Hi, I'm Max!

I'm a software developer who mainly works in PHP, but also dabbles in Ruby and Go. Technical topics that interest me are monitoring, security and performance.

During the day I solve challenging technical problems at Something Digital where I mainly work with the Magento platform. I also blog about tech, work on open source and hunt for bugs.

If you'd like to get in touch with me the best way is on Twitter.