PHP Tutorial - PHP Array






An array is a normal PHP variable, but we can put other variables inside it. Each variable inside an array is called an element. Each element has a key and a value, which can be any other variable.

Two types of arrays

PHP supports two types of arrays:

  • Indexed arrays - where each element is referenced by a numeric index, usually starting from zero. For example, the first element has an index of 0, the second has an index of 1, and so on
  • Associative arrays (hash or map) - each element is referenced by a string index.




PHP Create Indexed Array

Indexed arrays is arrays where each element is referenced by a numeric index, usually starting from zero. For example, the first element has an index of 0, the second has an index of 1, and so on

PHP has built-in support for arrays, and we can create array using the array() function.

$myarray = array(element0, element1, element2,element3,...);

Here is a basic example:


<?PHP
$myarray = array("PHP", "Java", "Python","java2s.com"); 
$size = count($myarray); 
print_r($myarray); 
?>

The code above generates the following result.

On the first line, we create an array, the array() function. array() function takes a list of variables or values as its parameters, and returns an array containing those variables.

In that example, $myarray contains three elements.

There are our three values-PHP is at index 0 in the array (signified by [0]=>), Java is at index 1 in the array, and Python is at index 2 in the array.

You can store whatever you like as values in an array, and you can also mix values. For example: array("Foo", 1, 9.9, "java2s.com", $somevar).





Array interpolation

To print array data inside a string, we have to use braces {} around the variable. This next code shows how.


<?PHP
$myarray['foo'] = "bar";
print "This is from an array: {$myarray['foo']}";
?>

The code above generates the following result.

PHP Create Associative Arrays

PHP Associative Arrays are array with your own keys.

We can use array() function to create associative array.

$myarray = array("key1"=>"value1", "key2"=>"value2", ....); 

The following code creates a PHP associative array to hold the key value pair.


<?PHP
$myarray = array("a"=>"Apple", "b"=>"Bag", "c"=>"Cat"); 
var_dump($myarray); 
?>

The code above generates the following result.

PHP converts floating-point numbers to integers in the associative arrays, which essentially rounds them down.

Example - Create Associative Array with different type of values

The following PHP code creates an Associative Array with different type of values.


<?PHP
$myBook = array( "title" =>  "Learn PHP from java2s.com", 
                 "author" =>  "java2s.com", 
                 "pubYear" =>  2000 );   

?>

This creates an array with three elements:

  • "Learn PHP from java2s.com" , which has an index of "title";
  • "java2s.com", which has an index of "author";
  • and 2000 , which has an index of "pubYear".