Reputation: 335
I'm having to pass 3 variables (int) within a single numeric string called $id. To do this I'm creating $id using padding which I can then explode to get the variables. It has to be numeric otherwise I'd use underscores between the variables. I'm using eleven zeros as padding as I know the variables won't have that many zeros. So currently if I have:
$int_one = 1;
$int_two = 2;
$int_three = 3;
That would be:
$id = "1000000000002000000000003";
To create the new Id I use:
$id = $int_one . "00000000000" . $int_two . "00000000000" . $int_three;
And to separate the Id I use:
$int_one = 0;
$int_two = 0;
$int_three = 0;
if (strpos($id,"00000000000") !== false) {
$id = strrev($id); // Reversed so 0's in int's don't get counted
$id = explode("00000000000", $id);
// Set numbers back the right way
$int_one = strrev($id[2]);
$int_two = strrev($id[1]);
$int_three = strrev($id[0]);
}
This runs into problems when an individual variables is 0. Is there a way to overcome this or does it need a major rethink?
EDIT: $id
is supposed to be a numeric string not int
Needs to handle int variables between 0 - 2147483647
Upvotes: 0
Views: 111
Reputation: 180987
You can just use some string magic to assure that no number has more than one zero in a row, and delimit the values using '00'. This generates a numeric string that can be uniquely decoded no matter the size or composition of the ints.
$a = 100;
$b = 0;
$c = 120;
// Encode;
$id = str_replace('0', '01', $a).'00'
.str_replace('0', '01', $b).'00'
.str_replace('0', '01', $c);
// $id = "101010001001201"
// Decode;
$tmp = split('00', $id);
$a2 = intval(str_replace('01', '0', $tmp[0]));
$b2 = intval(str_replace('01', '0', $tmp[1]));
$c2 = intval(str_replace('01', '0', $tmp[2]));
// $a2 = 100, $b2 = 0, $c2 = 120
Upvotes: 2
Reputation: 2856
You could try this method:
$int_one = 1;
$int_two = 2;
$int_three = 3;
$id = $int_one * 1000000000000 + $int_two * 1000000 + $int_three;
// This will create a value of 1000002000003
To reverse the process:
// Get the modulo of $id / 1000000 --> 3
$int_three = $id % 1000000;
// Recalculate the base id - if you would like to retain the original id, first duplicate variable
// This would make $id = 1000002;
$id = ($id - $int_three) / 1000000;
// Again, get modulo --> 2
$int_two = $id % 1000000;
// Recalculate base id
$id = ($id - $int_two) / 1000000;
// Your first integer is the result of this division.
$int_one = $id;
Upvotes: 0
Reputation: 61467
Is there a way to overcome this or does it need a major rethink?
Yes, you'll need to rethink that. Why do you need to do it that way? Simply create a function with three parameters and pass the three ints in:
function foo($int1, $int2, $int3) {
}
Your example uses strings, not ints by the way, so you aren't even following your own requirements.
Upvotes: 1