Hudzilla.org - the homepage of Paul Hudson
Contents > Arrays Wish List | Report Bug | About Me ]

5.1     First steps: array(), count(), print_r(), var_dump(), and var_export()

This is NOT the latest copy of this book; click here for the latest version.

array array ( [mixed ...])

int count ( mixed var [, int mode])

bool print_r ( mixed expression [, bool return])

void var_dump ( mixed expression [, mixed expression [, mixed ...]])

mixed var_export ( mixed expression [, bool return])

PHP has built-in support for arrays of data, and there are two ways you can create an array: using the array function, or using a special operator, [ ].

Before we look at how arrays work, there are two key things you need to understand before you continue:

  • An array is a normal PHP variable like any others, but it works like a container - you can put other variables inside it

  • Each variable inside an array is called an element . Each element has a key and a value , which can be any other variable.

Now, consider this PHP code:

<?php
    $myarray
= array("Apples", "Oranges", "Pears");
    
$size = count($myarray);
    
print_r($myarray);
?>

On line one we see the most basic way to create an array, the array() function. The array() function takes a minimum of one parameter (and a maximum of as many as you want), and returns an array containing those variables. That's right - $myarray now contains all three variables. Line two contains a new function, count(), that returns the number of elements consisting in the array passed to it as its only parameter - in the example we pass in my $myarray, then store the number of elements (three) in $size.

Author's Note: The array() function actually allows you to have a trailing comma after the last element, eg: array("Apples", "Oranges", "Pears",). This is rarely used in hand-written code, but it can make generating code much easier.

Line three contains another new function, print_r(). This takes just one parameter, but it outputs detailed information about a variable, such as it is type, length, and contents. In the case of arrays, print_r() iteratively outputs all elements inside the array - it is a good way to see how arrays work.

Here is the output of print_r() from the above code:

Array
(
[0] => Apples
[1] => Oranges
[2] => Pears
)

As you can see, there are our three variables - Apples is at index 0 in the array (signified by "[0]=>"), Oranges is at index 1 in the array, and Pears is at index 2 in the array. Note that if you are running your scripts through a web browser as opposed to from the command-line, you may find it help to put a HTML <PRE> tag before your print_r() calls, as this will format them for easier reading.

Using the proper array terminology defined earlier, the 0, 1, and 2 indices are the keys of each element, the "Apples", "Oranges", and "Pears" are the values of each element, and the key and the value considered together are the elements themselves.

Note that you can provide a second parameter to print_r(), which, if set to true, will make print_r() pass its output back as its return value, and not print anything out. To achieve the same output using this method, we would need to alter the script to this:

<?php
    $myarray
= array("Apples", "Oranges", "Pears");
    
$size = count($myarray);
    
$output = print_r($myarray, true);
    print
$output;
?>

You can store whatever you like as values in an array, and you can mix values also. For example: array("Foo", 1, 9.995, "bar", $somevar). You can also put arrays inside arrays, but we will be getting on to that later.

There is a similar function to print_r(), which is var_dump(). It does largely the same thing, but a) prints out sizes of variables, b) does not print out non-public data in objects, and c) does not have the option to pass a second parameter to return its output. For example, altering the first script to use var_dump() rather than print_r() would give the following output:

array(3) {
    [0]=>
    string(6) "Apples"
    [1]=>
    string(7) "Oranges"
    [2]=>
    string(5) "Pears"
}

In there you can see var_dump() has told us that the array has three values, and also prints out the lengths of each of the strings. For teaching purposes, var_dump() is better as it shows the variable sizes, however you will probably want to use print_r() in your own work.

Finally, there is the function var_export(), which is similar to both var_dump() and print_r(). The key difference with var_export(), however, is that it prints out variable information in a style that can be used as PHP code. For example, if we had use var_export() instead of print_r() in the test script, it would have output the following:

array (
    0 => 'Apples',
    1 => 'Oranges',
    2 => 'Pears',
)

Note there is an extra comma after the last element, however this is ignored by PHP and you can copy and paste that information directly into your own scripts, like this:

<?php
    $foo
= array (
    
0 => 'Apples',
    
1 => 'Oranges',
    
2 => 'Pears',
);
?>




<< 5 Arrays   5.2 Associative arrays >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
A PHP User - 13 Oct 2008

RE the person who suggested using the <pre> tags to give formatted output via var_export()

as in
print("<pre>");
var_export($form);
print("</pre>");

THANK YOU THANK YOU THANK YOU

A PHP User - 13 Oct 2008

RE the person who suggested using the <pre> tags to give formatted output via var_export()

as in
print("<pre>");
var_export($form);
print("</pre>");

THANK YOU THANK YOU THANK YOU

A PHP User - 13 Oct 2008

RE: var_export() output all going to one line, i.e. the information is not being properly formatted for output...

According to the documentation, var_export() should format the data in an organized manner, but for some reason when I use it to output the array structure, it is giving a stream of output that is not being formatted. Ideas?

Shafiq - 13 Oct 2008

it really helpful notes for me

A PHP User - 13 Oct 2008

it really helpful notes

A PHP User - 13 Oct 2008

In response to TxtEdMacs - 23 Sep 2006

var_dump() takes more than 1 parameter:

var_dump($myarray, true);
would dump $myarray and then the second parameter, "true", which it correctly writes as "bool(true)"

Romack L. Natividad / romacknatividad@yahoo.com - 13 Oct 2008

//
// show information of an object or an array
//
function print_in_table($res){
echo "<table border=5 style=\"background-color: gold\">";
foreach($res as $key => $value){
echo "<tr style=\"font: 12px sans\">".
"<td style=\"border-style: outset\">$key</td>".
"<td style=\"border-style: outset\">".
"<pre style=\"font: 12px sans\">";
print_r($value);
echo "</pre></td></tr>";
}
echo "</table>";
}

php is awesome - 13 Oct 2008

To get array keys and values to print on separate lines, I use <br\n> in my programming.

TxtEdMacs - 13 Oct 2008

Reading the documentation again, more closely - the bool (true) after the array could just be another value not the return value I thought it to be. [See my comment just below.]

TxtEdMacs - 13 Oct 2008

Odd - regarding var_dump(), I rewrote the code before carefully reading the text. In running this:

<?php
$myarray = array("Apples", "Oranges", "Pears");
$size = count($myarray);
$output = var_dump($myarray, true);
print $output;
?>

The results were this:

array(3) {
[0]=>
string(6) "Apples"
[1]=>
string(7) "Oranges"
[2]=>
string(5) "Pears"
}
bool(true)

which implies var_dump is not fully documented. Removing the second parameter, the result exactly matches the sample as shown.

A PHP User - 13 Oct 2008

PHP abUser - as it says in the text above, wrap the output in pre tags:

print("<pre>");

var_dumb($variable);

print("</pre>");

A PHP abUser - 13 Oct 2008

When I use print_r or var_dump, the output is all on one line rather than each key/value being on a new line.
Does anyone know how to get round this?

Thanks.

dircc@pmb.ro - 13 Oct 2008

for a multiarray in 2 stages (each element being a array), what are the expressions for count() and for reset() ?



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is ten plus three?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow