skip to Main Content

I have a program that prints result as an array:

Array
(
    [2019] => 15.63
    [2020] => 4.96
    [2021] => 42.92
)

But I need to print it in such form:

[2019 => 15.63, 2020 => 4.96, 2021 => 42.92]

How could it be done? Do I have to make another program for it? Or is there any easier way?

2

Answers


    1. You have the default print_r() output. There is no option for formatting this, but you can transform the output as needed.

    2. Convert the array to JSON and do some replacements. You can go further and replace the quotes and spaces after comma.

    $array = [10 => 11.22, 20 => 22.33, 30 => 33.44];
    echo str_replace([':', '{', '}'], ['=>', '[', ']'], json_encode($array));
    
    ["10"=>11.22,"20"=>22.33,"30"=>33.44]
    
    1. But that’s not a good choice. Better is to reconstruct the output by the transforms of your needs.
    $format = function ($key, $value) {
        return "$key => $value";
    };
    echo '[', join(', ', array_map($format, array_keys($array), $array)), ']';
    
    [10 => 11.22, 20 => 22.33, 30 => 33.44]
    
    Login or Signup to reply.
  1. My advice will be very specific to your flat input array. It seems that you would like the output from var_export () but without the old skool array syntax and without the multiline formatting.

    The following will use modern brace syntax and replace the newlines with single spaces. My snippet is not designed for multidimensional arrays and can be broken if your keys or values contain newlines. For your basic associative array, it is safe to use.

    Code: (Demo)

    $array = [10 => 11.22, 20 => 22.33, 30 => 33.44];
    echo preg_replace(
             ['/^array (s+/', '/,?R?)$/', '/$R  /m'],
             ['[',              ']',          ' '],
             var_export($array, true)
         );
    

    Output:

    [10 => 11.22, 20 => 22.33, 30 => 33.44]
    

    If you require more complicated data sets to be reformatted, then this would become a far less trivial task that should consider implementing a tokenizer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search