I have an array with some missing keys like so:
[php]
Array
(
[0] => a
[1] => b
[2] => c
[4] => d
[6] => e
[7] => f
)
[/php]
i want to combine the values of keys that are in order, to end up with this:
[php]
Array
(
[0] => abc
[4] => d
[6] => ef
)
[/php]
what is the easiest way to accomplish this?
Tried and tested to be working. I put some small comments in there, but if you need more explanation on how it works, let me know.
[php]$letters = array(
0 => “a”
,1 => “b”
,2 => “c”
,4 => “d”
,6 => “e”
,7 => “f”
);
$new_arr = array();
$last = false;
foreach($letters as $key => $val)
{
$new = !(isset($letters[$key-1])); //if we can’t find an element with a key 1 lower, it can’t have been used, so we’ll be making a new element
if($new === true)
{
//here we make a new element and save it’s key in the $last variable
$new_arr[$key] = $val;
$last = $key;
}
else
{
$new_arr[$last] .= $val;
}
}[/php]