Print Array in PHP
There are various methods and commands used in PHP to print an array of elements. They are different in the way they print the array elements.
I will cover three main ones I usually use.
Lets assume an array as follows to explain the various types of printing.
$array = array(
'string' => 'abcd',
'bool' => false,
'num' => 4,
array(1,3,4,'2343',true)
);
- var_dump The syntax for the function is var_dump($array) and the result is array(4) { ["string"]=> string(4) "abcd" ["bool"]=> bool(false) ["num"]=> int(4) [0]=> array(5) { [0]=> int(1) [1]=> int(3) [2]=> int(4) [3]=> string(4) "2343" [4]=> bool(true) } }
- print_r The syntax for the function is print_r($array) and the result is Array ( [string] => abcd [bool] => [num] => 4 [0] => Array ( [0] => 1 [1] => 3 [2] => 4 [3] => 2343 [4] => 1 ) )
- var_export The syntax for the function is var_export($array) and the result is array ( 'string' => 'abcd', 'bool' => false, 'num' => 4, 0 => array ( 0 => 1, 1 => 3, 2 => 4, 3 => '2343', 4 => true, ), )
To see the difference check the way the array elements are displayed and how Boolean and nested arrays are handled. var_export is used for reusing that printed array in a php file. This is useful when you generate an array which should be used in another php code where you can easily copy paste and use.
Related Posts:
Page 1 of 2 | Next page