Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to inspect the contents of a variable

Short answer

var_dump() shows a value together with its type:

<?php
 
var_dump('42', 42, 42.0, null);

Output:

string(2) "42"
int(42)
float(42)
NULL

An array in a readable form

print_r() is shorter but shows no types:

<?php
 
print_r(['name' => 'Anna', 'tags' => ['php', 'sql']]);

Output:

Array
(
    [name] => Anna
    [tags] => Array
        (
            [0] => php
            [1] => sql
        )
 
)

To the log instead of the page

On a live site visitors would see debug output. A second argument of true returns the text as a string — it can be written to the log:

<?php
 
$user = ['id' => 7, 'name' => 'Anna'];
 
$text = print_r($user, true);
 
echo strlen($text) > 0 ? 'ready for error_log()' : '';

Output:

ready for error_log()

Functions used in this recipe

  • var_dump — Prints the type and the value — for debugging.
  • print_r — Prints a value in a readable form.
  • error_log — Writes a message to the error log.

Thanks for reading!

Donate to the site — we work hard for you.