Last active
January 28, 2023 16:48
-
-
Save av01d/77680d58f067e885b5ce0b814680b5b2 to your computer and use it in GitHub Desktop.
PHP Base62 encoder/decoder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Base62 { | |
private $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
public function base62Encode(int $num): string { | |
$res = ''; | |
do { | |
$res = $this->chars[$num % 62] . $res; | |
$num = (int)($num / 62); | |
} while ($num); | |
return $res; | |
} | |
public function base62Decode(string $num): int { | |
$limit = strlen($num); | |
$res = strpos($this->chars, $num[0]); | |
for ($i = 1; $i < $limit; $i++) { | |
$res = 62 * $res + strpos($this->chars, $num[$i]); | |
} | |
return $res; | |
} | |
} // End class | |
$inst = new Base62(); | |
var_dump($inst->base62Encode(123456)); // Result: w7e | |
var_dump($inst->base62Decode('w7e')); // Result: 123456 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment