h404
h404

Reputation: 37

Reduce a flat array with an even number of elements to a flat array of strings containing hyphenated pairs

I have simple array:

Array(1,3,c,4,a,24,m,4)

I need to group the two values for the key like:

Array
(
    [0] => 1 - 3
    [1] => c - 4
    [2] => a - 24
    [3] => m - 4
)

Upvotes: -3

Views: 44

Answers (3)

Xorifelse
Xorifelse

Reputation: 7911

As suggested by Mark Baker, split in groups of 2 as your question can be resolved by this:

$array = array(1, 3, 'c', 4, 'a', 24, 'm', 4);
$chunked = array_chunk($array, 2);

$result = [];
foreach ($chunked as $chunk) {
    $result[] = implode(' - ', $chunk);
}

print_r($result);

// or go classy
$result2 = []
for ($i = 0; $i < count($array); $i += 2) { // +2, groups of 2.
  $result2[] = $array[$i] . ' - ' . $array[$i + 1];
}

print_r($result2);

Upvotes: 0

mickmackusa
mickmackusa

Reputation: 48031

I might concatenate references or chunk and implode the data. Demo

$array = [1,3,'c',4,'a',24,'m',4];

$result = [];
foreach ($array as $v) {
    if (!isset($ref)) {
        $result[] =& $ref;
        $ref = $v;
    } else {
        $ref .= " - $v";
        unset($ref);
    }
}

var_export($result);

Or

var_export(
    array_map(
        fn($pair) => implode(' - ', $pair),
        array_chunk($array, 2)
    )
);

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92884

Concise solution with foreach loop and array_values function:

$arr = [1,3,'c',4,'a',24,'m',4];
$result = [];

foreach ($arr as $k => $v) {
    ($k % 2 == 0)? $result[$k] = $v : $result[$k-1] .= " - $v";
}

var_dump(array_values($result));

// the output:
array (size=4)
  0 => string '1 - 3' (length=5)
  1 => string 'c - 4' (length=5)
  2 => string 'a - 24' (length=6)
  3 => string 'm - 4' (length=5)

Upvotes: 0

Related Questions