Array: Lesson Part 1

Learn PHP arrays and how easy it is to store and organize complex data structures.

Introduction:

You may already know about PHP variables, and how unfortunately you can only store only one value at a time. But now lets move on to a new type of variable called an array. Arrays allow you to store as many values as you want inside it. It keeps track of the information by indexing the data by a number or a string. Think of a variable as a bottle of soda. And think of an array as a case of sodas, or a warehouse of sodas.
Elements in an Array Example:

Values: (“Bart”, “Sharon”, “Betty”)
Index Number: (0, 1, 2)
Which Element? (First, Second, Third)

The index always starts as zero. This easy to forget, so if you did not get what you expected when outputting a value in an array, the chances are that you started counting at one instead of zero.

Creating Arrays Use the Array() Function:

$states = array (“NY”, “PA”, “CA”)

You can now access the second element by the index “1”:

echo “$state[1]”;

This will display as “PA”.
Creating or Adding to Arrays with Array Identifier:

$states[] = “NY”;
$states[] = “PA”;
$states[] = “CA”;

The values will be listed in the same line order as to when they where set. You can also place them in the order you want by using the index number placed inside the square brackets like so:

$states[1] = “PA”;
$states[2] = “CA”;
$states[0] = “NY”;

When using the identifier with an index number to set the value, be sure never to set the index number too high. For example, if there are only 3 elements in an array and you want to add a new value to the end of the array, you must use the index number [3].

The safe way to achieve this would be not to use an index number and just leave the square brackets blank like so:

$state = array(“NY”, “PA”, “CA”);
// add a new state to the end of the our array of states
$state[] = “OH”;


Conclusion:

This is just Part 1 of PHP Array Tutorials for developing your on web programs. Be sure to read our Part 2 “Complex Data Arrays” to help you master arrays and create more dynamic web applications.

You may also like...

2 Responses

  1. Fade says:

    Hey that helped me alot. THanks dude

  2. Joe Tanory says:

    The lesson on arrays was clear and informative.

Leave a Reply