Converting a string to a number consistently using PHP

Say you want to convert strings to numbers such that a string will always convert to the same number. So for example the string
“red” will always convert to 2 or the string “blue” will always convert to 1. You don’t know which strings you are going to get and the exact number they convert to doesn’t matter just that it always converts to the same number. The reason you want to do this is to pick a value from an array based on that string-converted-to-a-number i.e. you want to use the string-converted-to-a-number as the array’s index or key. How do you do that conversion using PHP?

Now there are a few ways you could do this. You could take the first letter of the string and convert it to it’s ascii code. Then use the mod operator to bring it into the desired range:

$str    = 'test';
$max    = 4;
$number = ord( substr( $str, 0, 1 ) ) % 4 + 1;
echo $number;

The above code will execute pretty fast and give you a result between 1 and 4. But it’s lacking in one aspect. It only takes into account the first letter in the string. Not all letters are used equally in the English language. Some letters are used more often at the start of a word so you will get disproportionate results.

To take all the letters into account you have to use crc32 function. This runs a mathematical formula on the string and converts it into a number that way. In other words it’s a hashing function.

$str    = 'test';
$max    = 4;
$number = crc32( $str ) % 4 + 1;
echo $number;

crc32 is a lot slower than the ord function but it takes the entire string into account.

Different content based on domain name

So in what scenario do you need to convert a string to a number using PHP? Say you want to rotate content based on a site’s domain name. Maybe rotate credit links on themes you make available for free download and use. In such a situation you want to give equal exposure to each link but also want only one link to show up on each site. So this is how you can do that:

function credit_link() {
	$links = array( 0 => array(
			1 => array(
					'URL' => '',
					'title' => 'Abdussamad'
			2 => array(
					'title'=>'Website theme'
			3 => array(
	$str = $_SERVER[ 'SERVER_NAME' ];
	//strip www. i.e. normalize string
	if ( substr( $str, 0, 4 ) == 'www.' ) {
  		$str = substr( $str, 4 );
	//convert the URL to a number.
	$hash = crc32( $str ) % count( $links ) ;
	$link= "<a href='http://{$links[$hash]['URL']}' title='{$links[$hash]['title']}'>{$links[$hash]['title']}</a>";
	echo $link;

The above code is pretty simple. It outputs one link per domain name and even strips out the www. portion to prevent different links from showing up on the same site. This allows you to rotate links on different sites.

Leave a Reply

Your email address will not be published. Required fields are marked *