Kathmandu,Nepal
Kathmandu,Nepal

Difference between print_r and var_dump in PHP

var_dump() and print_r() are both built-in functions in PHP that can be used to display the contents of a variable. However, they have some key differences:

1. print_r() Function: This function is a built-in function in PHP and is used to print information stored in a variable in a human-readable format. It is typically used for debugging purposes to see the contents of an array or object. It provides less detailed information about a variable compared to var_dump().

Example 1:

<?php
// Array with subjects
$array = array(
'0' => "PHP",
'1' => "Python",
'2' => "java",
);

// Display array values
print_r($array);
?>

Output:
Array
(
[0] => PHP
[1] => Python
[2] => java
)

Example 2:

<?php
$array = array ('x' => 'PHP', 'y' => 'Python', 'z' => array ('a', 'b', 'c'));
print_r ($array);
?>

Output:
Array
(
[x] => PHP
[y] => Python
[z] => Array
(
[0] => a
[1] => b
[2] => c
)
)

2.var_dump() Function: This function is a built-in function in PHP and is used to display the data type and value of a variable. It also shows the number of elements in an array and the properties of an object. It provides more detailed information about a variable compared to print_r() Function.
Example 1:

<?php
// Array with subjects
$array = array(
'0' => "PHP",
'1' => "Python",
'2' => "java",
);

// Display array values
print_r($array);
?>

Output:
array(3) {
[0]=>
string(3) "PHP"
[1]=>
string(6) "Python"
[2]=>
string(4) "java"
}

Example 2:

<?php
$x = array(1, 2,3, array("a", "b", "c","d"));
var_dump($x);
?>

Output:
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
[3]=>
string(1) "d"
}
}

Leave a Comment

Your email address will not be published. Required fields are marked *

×