PHP - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

PHP Arrays

PHP Arrays

shape Description

PHP Arrays are a collection of variables, which stores multiple values of same or different datatype at a time. (or) Array is a collection of types.The array can hold any type.It can contain strings,integers,floating points and even other arrays.Each of these values inside an array can be accessed with a related key value pair.An array can be created in two ways.array() or array[].Array() function can be used to create an array in PHP.

shape Syntax

$array_name = array("value1", "value1", "value1", "value1");

Indexed Arrays

shape Description

Every array element in the indexed array stores a numeric index. It can be created in two ways. 1) The assignment of index is done automatically. [php] <?php // Define an indexed array $names = array("John", "Mike", "Brake"); ?> [/php] 2) The assignement of index is done manually. [php] <?php $colors[0] = "John"; $colors[1] = "Mike"; $colors[2] = "Brake"; ?> [/php]

shape Example

[php] <!DOCTYPE html> <html> <body> <?php $names = array("John", "Mike", "Brake", "Hussey"); echo "Names in the Array : " . $names[0] . ", " . $names[1] . ", " . $names[2] . ", " . $names[3] . "."; ?> </body> </html> [/php] Output:

Associative Arrays

shape Description

The keys assigned to the values can be arbitrary and user defined strings in the associative array.

shape Example

[php] <!DOCTYPE html> <html> <body> <?php $age = array("John"=>"24", "Mike"=>"16", "Brake"=>"26", "Hussey"=>"26"); echo "John Age : ".$age['John']."<br/>"; echo "Mike Age : ".$age['Mike']."<br/>"; echo "Brake Age : ".$age['Brake']."<br/>"; echo "Hussey Age : ".$age['Hussey']."<br/>"; ?> </body> </html> [/php] Output:

Multidimensional Arrays

shape Description

The an array in which every element has the eligibility to become an array and every element in the sub-array follows the same or further contain array within itself and so on.

shape Example

[php] <!DOCTYPE html> <html> <body> <?php $details = array ( array("Peter","B.Tech",2012), array("John","B.Tech",2010), array("Harry","M.Tech",2013) ); echo "Name : ".$details[0][0]." -> Qualification: ".$details[0][1].", year: ".$details[0][2].".<br/>"; echo "Name : ".$details[1][0]." -> Qualification: ".$details[1][1].", year: ".$details[1][2].".<br/>"; echo "Name : ".$details[2][0]." -> Qualification: ".$details[2][1].", year: ".$details[2][2].".<br/>"; ?> </body> </html> [/php] Output:

Summary

shape Key Points

  • PHP Arrays are collection of types.
  • Indexed arrays: These arrays has a numeric index.
  • Associative arrays: These arrays has named keys.
  • Multidimensional arrays: These arrays has one or more arrays.