PHP – print array in one line

At times for large array values we want to log them in one line for better readability. Logging an array in one line is also grep friendly. Here are few approached and php code snippets.

Print array in one line using print_r and str_replace

<?php
function my_print_r ($x) {
  return str_replace(PHP_EOL, '', print_r($x, TRUE));
}
$a = array('a' => "val\na", 'b' => 'valb');
echo "=====Before removing newline=====\n";
print_r($a);
echo "=====After removing newline=====\n";
echo my_print_r($a);
?>
=====Before removing newline=====
Array
(
    [a] => val
a
    [b] => valb
)
=====After removing newline=====
Array(    [a] => vala    [b] => valb)
Env: PHP 5.5.9 (Linux)

Print array in one line using json_encode

We’ll php PHP_EOL for replacing all newlines.

<?php
function my_print_r2 ($x) {
  return json_encode($x);
}
$a = array('a' => "val\na", 'b' => 'valb');
echo "=====Before removing newline=====\n";
print_r($a);
echo "=====After removing newline=====\n";
echo my_print_r2($a);
?>
=====Before removing newline=====
Array
(
    [a] => val
a
    [b] => valb
)
=====After removing newline=====
{"a":"val\na","b":"valb"}
Env: PHP 5.5.9 (Linux)

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments