PHP Arrays

Ok I have been dealing with people that just don’t understand arrays… I don’t know why they cant grasp the concept but I am going to explain single and multi-demential arrays and how to use them.

PHP Arrays

An array is a list of items that are tracked by an index number (or name “key”). Here is an example of a list of names:


<?php
$array = array("Joe", "Bill", "Susan", "Kim");
echo "<pre>";
print_r($array);
echo "</pre>";
?>

The above lines of code create an array (list) of names in order. In programming and most engineering fields we start counting at 0 and not 1. So the “First” item in the array is “Joe” but we call it the value at index 0. There are four items in the array, most people would count it like this:

1 => “Joe”, 2 => “Bill”, 3 => “Susan”, 4 => “Kim”

but programmers count it like this:

0 => “Joe”, 1 => “Bill”, 2 => “Susan”, 3 => “Kim”

Ok, so now when we run the code the “


” tags will format the output for us and make it more readable. Another note, I echoed the

 tags to the screen but you can't echo an Array. You must use print_r() to display the contents of the array to the screen as text.


ARRAY
{
0 => "Joe"
1 => "Bill"
2 => "Susan"
3 => "Kim"
}

Now if we want the value of index #2 we would do this:


echo $array[2];

We would see "Susan". Now this can get confusing with the numbers being shifted so I introduce Associative Arrays.


<?php
$array = array("Boss" => "Joe", "Janitor" => "Bill", "Nurse" => "Susan", "Customer" => "Kim");
echo "<pre>";
print_r($array);
echo "</pre>";
?>

You will notice that the main difference is the addition of a named index. So now we can call this


echo $array["Boss"];

We will get "Joe" as our output. All the examples I have shown are single demential arrays. Moving on...

Multi-demential Arrays are Arrays that have Arrays inside of them, observe:


<?php
$array = array("Bosses" => array("Joe", "Matt"), "Customers" => array("Bill", "Susan", "Kim") );
echo "<pre>";
print_r($array);
echo "</pre>";
?>

Now we have a list of positions that have a list of people.


ARRAY
{
"Bosses"
{
0 => "Joe"
1 => "Matt"
}

"Customers"
{
0 => "Bill"
1 => "Susan"
2 => "Kim"
}
}

Now, to get this data we do this:


echo $array["Bosses"][0];
echo $array["Customers"][2];

This will output "Joe: and "Kim". We can make this an associative array and make it a little easier.


<?php
$array = array("Bosses" => array("East Boss" => "Joe", "West Boss" => "Matt"), "Customers" => array("Rich" => "Bill", "Poor" => "Susan", "Avg" => "Kim") );
echo "<pre>";
print_r($array);
echo "</pre>";
?>

Now we can get our data like this:


echo $array["Bosses"]["East Boss"]; // output will be "Joe"
echo $array["Customers"]["Poor"]; // output will be "Susan"

I hope this helps anyone that is confused.

Leave a Reply

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