Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Functions Function Returns and More Returning Values

print_r

Hello,

Can you please tell me the difference between print_r ()and var_dump(). I notice that the the instructor stored an array in a function and used print_r() to ouput the value of the array stored in the function.

I am not sure of the meaning of print_r and when to use it in actual code, and the difference between print_r and var_dump.

Thanks!

3 Answers

geoffrey
geoffrey
28,736 Points

I use both for debugging purposes, var_dump() includes the information such as the type of the variable or expression (boolean, string, int)...While print_r() doesn't give that kind of information. It's good idea to use it if you know the type of elements you have in your array.

More info here

Edit:

Oğulcan Girginc Yes, you use the one you want, It's just a matter of choice in this case.

Oğulcan Girginc
Oğulcan Girginc
24,848 Points

Thanks for that article geoffrey! A quick question: I don't need to use print_r, right? Just to be sure, I can use var_dump even though I know the type?

Hi there,

The difference between print_r() and var_dump() is the following:

// print_r() The print_r() displays information about a variable in a way that's readable by humans. array values will be presented in a format that shows keys and elements. Similar notation is used for objects.

// var_dump() The var_dump() displays structured information about variables/expressions including its type and value. Arrays are explored recursively with values indented to show structure. It also shows which array values and object properties are references.

Hope this helps with answering your question.

Regards, Liam Norris

Hello guys,

thanks for your help! Geoffrey the article really helped. By the way what does "recursive mean" Liam mentionned and the article mentions it. Here is the section in the article that mentions 'recursive'

"Note that var_export can not handle reference cycles/recursive arrays, whereas var_dump and print_r check for these."