Compress PHP array of characters to shorter array with a-z, A-Z, 0-9


I have a PHP array like this:


How can I convert this to:


There will only be standard ASCII characters – nothing fancy. Every character can only appear once.


One possible solution is to compare the current character to the incremented value of the previous one. If the current character is not consecutive, then the increment the range index.

$ranges = [];
$i = -1;
$previous = '';
foreach ($characters as $char) {
    $test = $previous;
    $i += (++$test == $previous || $test != $char);
    $ranges[$i] = isset($ranges[$i]) ? $ranges[$i][0] . "-$char" : $char;
    $previous = $char;

The boolean expression (++$test == $previous || $test != $char) will evaluate to int 0 or 1 when it is used with the += operator.

The first part, ++$test == $previous, tests that the previous character actually can be incremented. If it can’t, then that character isn’t an ASCII alphanumeric (the only characters affected by the ++ operator).

I initialized the range index $i to -1 because the first iteration will always increment it to 0.

Answered By – Don't Panic

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published