hex2bin 7 php<5.4

Standard

Another annoying thing; working on a server that has an old version of php. If you cant update, you cant use all the lovely new core functions that, well, that make life a bit less of a headache.

I came across the need to use the Unirest ‘Lightweight HTTP Request Client Libraries’ (as it describes its self – basically Unirest is a set of lightweight HTTP libraries that can make talking to an API a whole lot easier – especially if it uses any forms of security.

Well this library needed to use hex2bin – which i couldn’t being on a server tied to 5.3.3 (or so).

PHP and the likes of stackoverflow to the rescue.

function hex2bin($hexstr)
{
	$n = strlen($hexstr);
	$sbin="";
	$i=0;
	while($i<$n)
	{
		$a =substr($hexstr,$i,2);
		$c = pack("H*",$a);
		if ($i==0){$sbin=$c;}
		else {$sbin.=$c;}
		$i+=2;
	}
	return $sbin;
 
}

so this…

return array_combine(array_map('hex2bin', array_keys($values)), $values);

became this…

return array_combine(array_map('self::hex2bin', array_keys($values)), $values);