-3

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?

babygroot
  • 19
  • 6
  • Related: [How to print an Array on one line](https://stackoverflow.com/q/33721632/2943403) and [Remove linebreaks from print_r output](https://stackoverflow.com/q/66965587/2943403) – mickmackusa Mar 04 '23 at 04:34
  • And [this answer](https://stackoverflow.com/a/12740398/2943403) from [Print array to a file](https://stackoverflow.com/q/2628798/2943403) – mickmackusa Mar 04 '23 at 05:10

2 Answers2

0
  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]
Markus Zeller
  • 8,516
  • 2
  • 29
  • 35
0

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.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136