Skip to content

Instantly share code, notes, and snippets.

@av01d
Last active January 28, 2023 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save av01d/77680d58f067e885b5ce0b814680b5b2 to your computer and use it in GitHub Desktop.
Save av01d/77680d58f067e885b5ce0b814680b5b2 to your computer and use it in GitHub Desktop.
PHP Base62 encoder/decoder
<?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