Rearranging characters in a 15-digit string with the ability to revert to the original string

376 Views Asked by At

I have numerous 15-digit numbers. I need to rearrange the digits in each string based on a set order to hide the composite identifiers. For example: convert 123456789123456 to 223134897616545

The method I am thinking of is:

  1. Extract each digit using $array = str_split($int)
  2. Create a new array with required order from $array above

But here is where I am stuck. How do I combine all digits of array to single integer? Also is this an efficient way to do this?

Also I need to know the order in which it was shuffled so as to retrieve the original number.

4

There are 4 best solutions below

2
rollingBalls On

Implode the array and cast it into an int.

(int) implode('',$array)

4
Thamilhan On

You are already half way. You can use join or implode:

$no = 123456789123456;
$no_arr = str_split($no);
shuffle($no_arr);
echo join($no_arr);   // implode($no_arr);

I get this randomly:

574146563298123

Resultant is string. You can convert to int by type casting: echo (int) join($no_arr);

0
cypherabe On

another aproach in maybe less lines:

$num = 1234;
$stringOriginal = (string) $num;
// build the new string, apply your algorithm for that as needed
$stringNew = $stringOriginal[1] . $stringOriginal[0] . $stringOriginal[3] . $stringOriginal[2];
$numNew = (int) $stringNew;

warning: this has no error handling, it's easy to mess up the indices and get an error because of that

0
mickmackusa On

This appears to be a task of obfuscation (not encryption) -- meaning that you only want to obscure the value or make it slightly harder to guess. The truth is that if you are not changing any of the characters, but merely shuffling them around, then a brute force technique can very easily try every combination of the characters in order to "happen upon" the correct one.

Security aside, use a 15-element array to re-map the characters. How you generate and store this map is up to you. Use the map to revert the shuffled string to its original value.

Code: (Demo)

$input = '123456789123456';

$map = [5, 8, 13, 2, 4, 11, 0, 14, 1, 7, 3, 12, 10, 6, 9];

$result = '';
foreach ($map as $offset) {
    $result .= $input[$offset];
}
echo "Rearranged: $result\n---\n";

$reverted = '';
asort($map);
foreach ($map as $offset => $notUsed) {
    $reverted .= $result[$offset];
}
echo "Reverted: $reverted";

Output:

Rearranged: 695353162844271
---
Reverted: 123456789123456