Intro to Arrays in PHP
August 26, 2005
PHP has the ability to use associative arrays. These are by far the most useful and versatile data structure in PHP (and debatably any language). Instead of using the more common indexed array, where integers are used to identify the elements of the array, you can use strings.
If you are writing PHP, you have to know associative arrays and feel good about them.
Here's an example showing some common uses:
Associative arrays are also the most readable and convenient way to deal with database results. Suddenly you have an array that is indexed by field name from the table. How could anything be cooler than that?
For debugging arrays, there is nothing more useful than print_r():
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
If you want to add an element to the end of an array you can use the [] notation (sort of like a stack push):
Output:
Array
(
[0] => Monkey
[1] => Alligator
[2] => Rabbit
)
Read More about PHP arrays on PHP.net.
Tags: array, arrays, associative, associative array, example, introduction, php, PHP.net, programming
Comments
4 Responses to “Intro to Arrays in PHP”
Got something to say?

[...] Comparing the two examples it’s clear how similar connecting to either database becomes. Also notice we’re setting the fetch mode to associative so we get back friendly associative arrays. The following is an example of how to query and get back results: [...]
[...] arrays [...]
[...] So, I took the form and started some known array debugging techniques, mainly a simple print_r($_POST) which showed all the array elements with proper values in IE, but with Firefox they all had the default form values. Strange. [...]
Hi
I am Lucy, I have found your website while searching for some info at Google. Your site has helped me in a big way.
G’night