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',
)
2
Answers
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).prints:
The old "transpose and flatten" technique. Just feed the input array to
array_map()
twice.Code: (Demo — includes other techniques too)