PHP Array
In PHP, array is made up of elements which are related and shared the same characteristics. Each element has a key and a value. Key in array is unique and can be string or numerical value. The key is used to look up the value of an element. The value of element can be a string, a number, a boolean value such as true or false or even another array.
Creating an array
Unlike other programming language such as C and Java, PHP does not require you to specify array's size when creating an array. PHP even does not require you to declare array variable before using it. To create an array you just specify an key between a pair of bracket and value as follows:
<?php
$languages[0] = "English"; // array of languages
$languages[1] = "French";
$languages[2] = "Chinese";
echo $languages[0]; // print the first element
echo $languages[1]; // print the second element
echo $languages[2]; // print the third element
?>
The code snippet above uses array languages which has three elements. If you use key as numerical value as index, you can omit it as follows:
<?php
$languages[] = "English"; // array of languages
$languages[] = "French";
$languages[] = "Chinese";
echo $languages[0]; // print the first element
echo $languages[1]; // print the second element
echo $languages[2]; // print the third element
?>
To create associative array, you use the same fashion except you have to specify key of element explicitly. For example, we can create RGB colors array as follows:
<?php
$colors["red"] = "#FF0000";
$colors["green"] = "#00FF00";
$colors["blue"] = "#0000FF";
echo $colors["red"]; // print the element with key is red
?>
Creating an array by using array() function
PHP provides array() function which allows you to create an array in similar fashion as above. For example, to create language array which contains three elements we do as follows:
<?php
$language = array("English","French","Chinese");
?>
To create an associative array we can use array() function with explicit keys defined for each element such as:
<?php
$colors = array("red"=>"#FF0000",
"green"=>"#00FF00",
"blue"=>"0000FF");
?>
Creating a range array by using range() function
PHP provides range() function to create range array and fill it with values. Here is the form of range() function:
range(int low,int high,[optional in step])
You specify the low, high values in integer and optional parameter step for distance between element values. For example to create an array of 10 integers, you can use range() function as follows:
<?php
$int = range(1,10);
for($i = 0; $i < 10;$i++)
print $int[$i];
?>
If you want to create an array which contain only even number, you can use range() function as follows:
<?php
$int = range(2,10,2);
for($i = 0; $i < 5;$i++)
print $int[$i];
?>