A few useful debugging functions
So now that you know what's a PHP array and what's a PHP variable, let's see a few functions that can help you get a good idea what's the content of a variable at any time .
print_r()
print() is a language construct, almost the same as echo and can be used instead of echo to print strings. print_r() on the other hand is a function that prints a variable recursively, meaning that it can print all elements of an array, even if it consist of other arrays.
Let's see an example:
$a = array(1, 2, 3, array(4, 5, 6)); echo $a; // prints "Array", not useful at all print $a; // same as above echo '<pre>' print_r($a); // the good stuff echo '</pre>'
So echo and print will output "Array", that's the best they can do, because they accept string input, not arrays. print_r() will output the array very nicely in a readable format, so that you know exactly what's the contents of the array. The output from the print_r() in the code above will be:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
)
Very useful when at some point in the development, you're no longer sure what exactly is in this array.
If you give a string or a number to print_r() instead of an array, it will act as a normal print call.
var_dump()
Similarly to print_r() you can get an idea of the contents of an array by using var_dump(). In addition to what print_r() gives, it will also report the size of an array (or sub-array) and will report the type of each value.
An example use of var_dump():
$a = array('one', true, 3.14, array(4, 5, 6));
echo '<pre>'
var_dump($a);
echo '</pre>'
The result is:
array(4) {
[0]=>
string(3) "one"
[1]=>
bool(true)
[2]=>
float(3.14)
[3]=>
array(3) {
[0]=>
int(4)
[1]=>
int(5)
[2]=>
int(6)
}
}
Given scalar data (not an array), var_dump() will behave similarly.
var_dump('one'); // string(3) "one"
You can pass as many values or variables to var_dump() as you want.
var_dump('one', 'two', 3);
The above will print:
string(3) "one" string(3) "two" int(3)
var_export()
var_export() is similar to var_dump() and print_r(), but with one significant difference - it produces valid PHP code. You can take the output and put it a PHP script as a normal PHP code.
$a = array('one', true, 3.14, array(4, 5, 6));
echo '<pre>'
var_export($a);
echo '</pre>'
The result is:
array (
0 => 'one',
1 => true,
2 => 3.14,
3 =>
array (
0 => 4,
1 => 5,
2 => 6,
),
)