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
You have the default
print_r()
output. There is no option for formatting this, but you can transform the output as needed.Convert the array to JSON and do some replacements. You can go further and replace the quotes and spaces after comma.
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)
Output:
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.