PHP for Beginners: Arrays
Arrays are used to store multiple values in a single variable. Each value in the array has its own index so that it can be easily accessed. In PHP, there are three kinds of arrays: Numeric Array (an array with a numeric index), Associative Array (an array where each ID key is associated with a value), and Multidimensional Array (an array that contains one or more arrays).
A numeric array stores each array element with a numeric index. There are two ways to create a numeric array:
1. Assign values and indices manually
<?php $product[0] = "Photoshop"; $product[1] = "CorelDraw"; $product[2] = "Maya"; $product[3] = "Flash"; ?>
2. Assign values and indices automatically
<?php
$product=array("Photoshop","CorelDraw","Maya","Flash");
?>
The following example shows the basic use of a numeric array:
<?php $product[0] = "Photoshop"; $product[1] = "CorelDraw"; $product[2] = "Maya"; $product[3] = "Flash"; echo $product[0] . " and " . $product[3] . " are property of Adobe."; ?>
This produces the following results:
Photoshop and Flash are property of Adobe.
In an associative array, each ID key is associated with a value. There are two ways to create an associative array:
1. Assign values and indices manually
<?php $years [ 'Company1' ] = 5; $years [ 'Company2' ] = 7; $years [ 'Company3' ] = 20; ?>
2. Assign values and indices automatically
<?php
$years=array(
"Company1"=>5,
"Company2"=>7,
"Company3"=>20);
?>
The following example shows the basic use of an associative array:
<?php $years [ 'Company1' ] = 5; $years [ 'Company2' ] = 7; $years [ 'Company3' ] = 20; echo "Company3 works for " . $years [ 'Company3' ] . " years."; ?>
This produces the following results:
Company3 works for 5 years.
In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. There are two ways to create an associative array, manually and automatically. The examples are same as the previous one with associative array. The following shows the basic creation of a multidimensional array:
<?php
$company = array
(
"Webelinx"=>array
(
"TapSong","iPocketFootball"
),
"Google"=>array
(
"YouTube","GooglePlus","GoogleMaps"
) );
?>
The array above would look like this if written to the output:
Array ( [Webelinx] => Array ( [0] => TapSong [1] => iPocketFootball ) [Google] => Array ( [0] => YouTube [1] => GooglePlus [2] => GoogleMaps ) )
The following example shows how to display a single value from the array above:
<?php echo "Is " $product['Webelinx'] [0] . "one of the Webelinx's product?"; ?>
The array above would look like this if written to the output:
Is TapSong one of the Webelinx's product?



