Reputation: 732
Suppose the array:
$prices = array (
'7.20',
'7.40',
'8.00',
'8.50',
'9.30',
'10.40',
'11.00',
'12.00',
'12.50',
'13.00',
)
Is there any clever, short (as close to an one-liner as possible) solution to copy each value to the next position, effectively doubling the array? So that the array above would become:
$prices = array (
'7.20',
'7.20',
'7.40',
'7.40',
'8.00',
'8.00',
'8.50',
'8.50',
'9.30',
'9.30',
'10.40',
'10.40',
'11.00',
'11.00',
'12.00',
'12.00',
'12.50',
'12.50',
'13.00',
'13.00',
)
Upvotes: 0
Views: 85
Reputation: 47904
The old "transpose and flatten" technique. Just feed the input array to array_map()
twice.
Code: (Demo -- includes other techniques too)
var_export(array_merge(...array_map(null, $prices, $prices)));
Upvotes: 1
Reputation: 5428
Here's one approach. The strategy is to (in a one-liner):
Use array_map
with a callback defined inline, to produce a "2D" array where each element is a pair of copies of the corresponding element in the given array.
Use array_merge(...$a)
to "flatten" that (as per https://stackoverflow.com/a/46861938/765091).
$prices = array ('7.20', '7.40', '8.00', '8.50', '9.30', '10.40', '11.00', '12.00', '12.50', '13.00',);
$res = array_merge(...array_map(function ($e) {return [$e, $e];}, $prices));
echo(implode($res, ', '));
prints:
7.20, 7.20, 7.40, 7.40, 8.00, 8.00, 8.50, 8.50, 9.30, 9.30, 10.40, 10.40, 11.00, 11.00, 12.00, 12.00, 12.50, 12.50, 13.00, 13.00
Upvotes: 2