PHP Arrays
By using variables, you can create a script that stores, processes, and outputs different information every time it is run. Unfortunately, you can store only one value at a time in a variable. Arrays are special variables that enable you to overcome this limitation.
An array enables you to store as many values as you want in the same variable. Each value is indexed within the array by a number or string. If a variable is a bucket, you can think of an array as a filing cabinet - a single container that can store many discrete items.
Why Use Arrays?
- Flexible: Can store two values or two hundred values without the need to define further variables.
- Efficient: Enables you to work easily with all its items through loops, sorting, or random access.
Each item in an array is commonly referred to as an element. Each element can be accessed directly via its index, which can be either a number or a string.
Creating Arrays
Defining Arrays with the array()
Construct
$subject = array("php", "java", "vb", "data structure"); echo $subject[2]; // Outputs "vb"
Arrays are indexed from zero by default, so the index of any element in a sequentially indexed array is always one less than the element's place in the list.
Defining or Adding to Arrays
$subject[] = "php"; $subject[] = "java"; $subject[] = "vb"; $subject[] = "data structure";
PHP automatically assigns index numbers, saving you from having to determine the next available slot.
Associative Arrays
Associative arrays are indexed with strings instead of numbers. Example:
$emp = array( "name" => "Sumit", "designation" => "Programmer", "age" => 30 ); echo $emp['name']; // Outputs "Sumit"
Using Associative Arrays
$marks = array( "Ram" => 80, "Lakshman" => 76, "Bharat" => 72, "Ravan" => 35, "Vibhishan" => 65 ); foreach ($marks as $name => $score) { echo $name . " = " . $score . "
"; }
Multidimensional Arrays
A multidimensional array is an array of arrays. Example:
$array = array( array(1, 2, 3), array(4, 5, 6), array(7, 8, 9) ); echo $array[1][2]; // Outputs "6"
Looping Through Arrays
Using foreach
with Indexed Arrays
$subject = array("PHP", "JAVA", "C", "Oracle"); foreach ($subject as $val) { echo $val . "
"; }
Using foreach
with Associative Arrays
$emp = array( "name" => "Rushikesh", "designation" => "Programmer", "age" => 33 ); foreach ($emp as $key => $val) { echo "$key = $val
"; }