Jump To Content

LearnHub




PHP: Arrays 2

Here is another PHP tutorial for PHP Arrays. Gotta love them and use them.
This one should be a little more simple than my first Array tutoiral.

At some point are another you will run into arrays in PHP or need to use them yourself. At first they may seem a little complicated, but really once you do a few yourself you see how easy it is to use them. Basically an array is a group of variables packed into one variable(array). They can come into handy when you find yourself defining variables like, $image1, $image2 and $image3. So lets get started.

Starting an Array:
PHP Code Example:
<?
// This creates an array called $names
$names = array('mike','scott','kyle','mark');
?>


Adding an Item:
PHP Code Example:
<?
// This adds the name "george" to the end our $names array
$names[] = 'george';
?>


In an array each item has a key to identify it, by default the first item's key is 0. So in our example mike would be 0 and kyle would be 2. The keys make it easy to use the items in your arrays. Here is an example of using the array items.

Array Usage:
PHP Code Example:
<?
// This is a complete example
$names = array('mike','scott','kyle','mark');
$names[] = 'george';
echo
"$names[1]; is 26 years old";
?>


This example would output: Scott is 26 years old

Associative Array:

You don't have to use the default numbering system for the keys, you can give your array any keyname you like. Here is a full example of using this type of array.

Array Usage:
PHP Code Example:
<?
// This is a complete example of a associative array.
$prices = array(
'fruit' => 'Apples',
'price' => '1.49',
'quanity' => '2'
);

echo (
"I bought $prices[quanity] $prices[fruit] for $prices[price]");

?>


This example would output: I bought 2 Apples for 1.49

Your Comment
Textile is Enabled (View Reference)