Datatypes in PHP - Arrays : Tutorial




5. Array datatype

Arrays are Compound data types.

In Compound data types we can have multiple items of the same type group into a single entity. An array is a just a variable which can hold more than one value.

An array in PHP is a ordered map (keys value association), hence an array in PHP can be a list (vector), hash table (an implementation of a map), dictionary, collection, stack or queue. As array values can be other arrays, trees and multidimensional arrays are also possible.

Syntax:
 array(
    key1  => value1, 
    key2 => value2,
    key3 => value3,
    key4 => value4,
    ...)

From PHP 5.4 onwards we have a shorter syntax for arrays [],
[
   "key1" => "value1",
   "key2" => "value2", 
    ...
 ];

We can also have arrays without keys (actually they are auto indexed)
<php

 $genre_array = array("Rock", "Pop", "Jazz", "HipHop","Folk");
 var_dump($genre_array);
 
?>
Output

array(5) {
[0]=> string(4) "Rock"
[1]=> string(3) "Pop"
[2]=> string(4) "Jazz"
[3]=> string(6) "HipHop"
[4]=> string(4) "Folk"
}

We can also assign values to arrays manually ,

[
   "key1" => "value1",
   "key2" => "value2", 
    ...
 ];

We can also have arrays without keys (actually they are auto indexed)
Like most programming languages, array index starts with 0 (zero)
$genre_array = array();

$genre_array[0]="Rock";
$genre_array[1]="Pop";
$genre_array[1]="Jazz";

?>
The Array values can be of any type, but keys should either be an integer or a string.

Below example shows how we can echo values of arrays.
<?php

$genre_array = array("Rock","Pop","Jazz");

echo "I like to listen to ".$genre_array[0]." music!, i also like listening to ".$genre_array[2];

?>
Output

I like to listen to Rock music!, i also like listening to Jazz

Note : Please look into Conditional Statements before cont. with further array part.

Foreach loop with Arrays

The foreach loop provides an easy way to iterate values for arrays.
There are two syntaxes:

Syntax 1 :
foreach (array_expression as $value)
    statement
Syntax 2 :
foreach (array_expression as $key => $value)
    statement

Examples :
<?php
$genre_array = array("Rock","Pop","Jazz");

//Syntax 1 example
foreach ($genre_array as &$value) {
    echo $value."<br>";
}

//Syntax 2 example
$genre_array = array(		
	"artist" =>"Nirvana",
	"album" => "Nevermind",
	"song" => "Smells like teen spirit");
	
foreach ($genre_array as $key => $value) {
	echo "Key : ".$key."  -  Value :".$value."<br>";
}
?>
Output