Skip to content

Instantly share code, notes, and snippets.

@Ydalb
Created March 24, 2020 17:02
Show Gist options
  • Save Ydalb/2f4240dc471528e04e11f0087e3c9ffc to your computer and use it in GitHub Desktop.
Save Ydalb/2f4240dc471528e04e11f0087e3c9ffc to your computer and use it in GitHub Desktop.
<?php
function compress(array $input) {
$result = [];
while (isset($input[0])) {
$i = 0;
do {
++$i;
$letter = array_shift($input);
} while (isset($input[0]) && $letter === $input[0]);
array_push($result, $letter, "{$i}");
}
return $result;
}
var_dump(compress(["a", "a", "b", "b", "b", "c", "c", "d"]));
/**
array(8) {
[0]=> string(1) "a"
[1]=> string(1) "2"
[2]=> string(1) "b"
[3]=> string(1) "3"
[4]=> string(1) "c"
[5]=> string(1) "2"
[6]=> string(1) "d"
[7]=> string(1) "1"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment