How to Print array in one line PHP

✔ Recommended Answer

  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));
  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]


Answered By: Markus Zeller

To print an array in one line in PHP, you can use the implode() function. This function takes two arguments: the first argument is the separator to be used between array elements, and the second argument is the array itself. 
The implode() function joins the elements of the $array array with a comma and a space as the separator, and then outputs the resulting string using the echo statement.


Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755