3

I can't get my PHP to pretty print using print_r. My output seems to appear all in one line rather than tiered.

I'm not sure what I'm missing. I've checked other q&a's on the site, but again, have come up empty handed. I asked my instructor and he suggested to use pretty_r(), which doesn't seem to be working for me. I've tried using the pre tags, but that hasn't seemed to work yet etiher.

Please bear with me if the questions are "incorrect". I'm just getting started, but this seems like a valuable thing to figure out early on as I start learning to code.

I'm taking a class and attempting to follow the instructor. His array returns look organized (image 1). I'm trying to replicate, but my output consistently appears on a single line (image 2).

Is there a reason why my code doesn't pretty print? I'm using Visual Studio Code and MAMP with Brave Browser. I get the same single-line (non-pretty) output in Safari, Firefox and Chrome as well.

$array = array(1,2,array(3,4,array(5,6,array(7,8,array(9,10)))));
print_r($array);
echo "<br/>";

Again, I've also tried wrapping print_r($array) in pre tags. But all that does is return the same thing plus the number one.

$array = array(1,2,array(3,4,array(5,6,array(7,8,array(9,10)))));
echo "<pre>".print_r($array)."</pre>";
echo "<br/>";

I've seen some extensions that refer to JSON, but I haven't understood what that is yet, so I can't make sense of the extensions being suggested (and I didn't want to just start installing a bunch of stuff).

1. Pretty print from instructor

2. My output NOT pretty printing

Ben C
  • 51
  • 6
  • try `print_r(var_dump($array))` – Banzay May 04 '20 at 09:57
  • 1
    _“But all that does is return the same thing plus the number one.”_ - that’s because you used `print_r` _inside_ of an `echo` statement. This needs to be either `echo "
    ".print_r($array, true)."
    ";`, or `echo "
    "; print_r($array); echo "
    ";`
    – CBroe May 04 '20 at 10:09
  • Thank you CBroe! That definitely did the trick. – Ben C May 08 '20 at 13:07

1 Answers1

2

Thank you @CBroe! Solved.

By changing the default return value to TRUE (for the return parameter), I'm getting pretty print!

THIS: echo "<pre>".print_r($array,true)."</pre>";

NOT THIS: echo "<pre>".print_r($array)."</pre>";

Ben C
  • 51
  • 6