tags:

views:

41

answers:

3

Hi,

I use the following method to pad out a ID for a property on our website:

function generateAgentRef($id,$length=5,$strPrefix='1'){
    return $strPrefix . str_pad($id,$length,0,0);
}

Basically it will prefix 1 and then pad out the id with 0's until the string reaches $length.

But, I now have a requirement to revert this process. For example if I have the following IDs: 100650,100359,100651,100622,100112,100687, how can I get the ID e.g. 650, 359, 651, 622, 112, 687?

Hope this explains what I'm trying to achieve.

The ID in the database will never start with 0, so I was thinking of iterating over the components of the string and detecting when I hit something other than 0 and then splitting the string.

+1  A: 

substract 100000 from the generated ref and intval() it could work if the length is 6 numbers exactly.

ChrisR
A: 

Hi try using this $a = substr($num,3);

here $num is the id you get $a will be your desired number i.e 100659 shortened to 659

ashishbhatt
The ID could be greater than 3 characters.
in that case you can try this $a = substr($num,1);// this to get rid of prefix$a = intval($a);// this will convert string 00659 into integer 659
ashishbhatt
A: 

Expanding on your initial function

function getAgentId($id, $length = 5, $strPrefix = 1){
    return $id - generateAgentRef(0, $length, $strPrefix);
}

$id = generateAgentRef(255);
echo $id, PHP_EOL; // 100255
echo getAgentId($id), PHP_EOL; //255
Gordon