skip to Main Content

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


  1. Here’s one approach. The strategy is to (in a one-liner):

    1. 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.

    2. 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
    
    Login or Signup to reply.
  2. 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)));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search