3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<?php function gdr_encode($val) { // all characters that json encode without escaping $chrs = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 !#$%&\'()*+,-.:;<=>?@[]^_`{|}~'; $base = strlen($chrs); $str = ''; while ($val > 0) { $str = $chrs[$val % $base] . $str; $val = (int)($val / $base); } return $str; } function gdr_decode($str) { // all characters that json encode without escaping $chrs = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 !#$%&\'()*+,-.:;<=>?@[]^_`{|}~'; $base = strlen($chrs); $map = array(); for ($i=0; $i<$base; $i++) { $map[$chrs[$i]] = $i; } $val = 0; for ($i=0; $i<strlen($str); $i++) { $val *= $base; $val += (int)$map[$str[$i]]; } return $val; } function duration($val) { if ($val < 24) { return sprintf('%d', $val).'h'; } if ($val < 24*10) { return sprintf('%1.1f', $val/24).'d'; } if ($val < 168*10) { return sprintf('%1.1f', $val/168).'w'; } //if ($val < 730*10) { // return sprintf('%1.1f', $val/730).'m'; //} return sprintf('%1.1f', $val/8760).'y'; } function insert(&$map, $n) { $map['1'.str_repeat('0', $n-1)] = true; $map[str_repeat('9', $n)] = true; } $map = array(0 => true); for ($i=1; $i<10; $i++) { insert($map, $i); } print_r(array_keys($map)); echo "\n\n"; $vals = array( 0, 1, 99, 100, 255, 256, 999, 1000, 9999, 10000, 65535, 65536, 99999, 100000, 250000, 500000, 750000, 999999, 1000000, 9999999, //4294967295, 4294967296 ); echo sprintf("%7s %7s %7s %4s\n", 'num', 'str', 'time', 'cmp'); foreach ($vals as $val) { $enc = gdr_encode($val); $dec = gdr_decode($enc); if ($dec !== $val) { echo "ERROR: $val => $enc => $dec\n"; } else { echo sprintf("%7d %7s %7s %4d\n", $dec, "\"$enc\"", duration($val), strlen($enc)+2-strlen($val)); } }
based on CJdBQ
Output for 4.3.0 - 7.1.0
Array ( [0] => 0 [1] => 1 [2] => 9 [3] => 10 [4] => 99 [5] => 100 [6] => 999 [7] => 1000 [8] => 9999 [9] => 10000 [10] => 99999 [11] => 100000 [12] => 999999 [13] => 1000000 [14] => 9999999 [15] => 10000000 [16] => 99999999 [17] => 100000000 [18] => 999999999 ) num str time cmp 0 "" 0h 1 1 "B" 1h 2 99 "BH" 4.1d 2 100 "BI" 4.2d 1 255 "C*" 1.5w 1 256 "C+" 1.5w 1 999 "K=" 5.9w 1 1000 "K>" 6.0w 0 9999 "BQ!" 1.1y 1 10000 "BQ#" 1.1y 0 65535 "H'f" 7.5y 0 65536 "H'g" 7.5y 0 99999 "L-`" 11.4y 0 100000 "L-{" 11.4y -1 250000 "dxk" 28.5y -1 500000 "7G+" 57.1y -1 750000 "{4Q" 85.6y -1 999999 "BaNz" 114.2y 0 1000000 "BaN0" 114.2y -1 9999999 "M;r7" 1141.6y -1