How to print an object in PHP
Created
Modified
Using print_r Function
The print_r() prints human-readable information about a variable. If given a string, int or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects.
print_r(mixed $value, bool $return = false): string|bool
$i = 10;
print_r($i);
$arr = array(
'title' => 'Apple Watch 7',
'views' => 1000
);
print_r($arr);
10 Array ( [title] => Apple Watch 7 [views] => 1000 )
Using var_dump Function
The var_dump() dumps information about a variable. This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
var_dump(mixed $value, mixed ...$values): void
$i = 10;
var_dump($i);
$arr = array(
'title' => 'Apple Watch 7',
'views' => 1000
);
var_dump($arr);
// This one returns the value of var_dump instead of outputting it.
function var_dump_ret($mixed = null) {
ob_start();
var_dump($mixed);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
int(10) array(2) { ["title"]=> string(13) "Apple Watch 7" ["views"]=> int(1000) }
Using var_export Function
var_export() gets structured information about the given variable. It is similar to var_dump() with one exception: the returned representation is valid PHP code.
var_export(mixed $value, bool $return = false): ?string
$i = 10;
var_export($i);
$arr = array(
'title' => 'Apple Watch 7',
'views' => 1000
);
$v = var_export($arr, true);
echo $v;
10 array ( 'title' => 'Apple Watch 7', 'views' => 1000, )