Tag: arrays

PHP Arrays

PHP array is a linear data structure that can store more than one values under a single variable.

Types of Arrays

There are three different kind of arrays and each array value is accessed using an ID, which is called array index.

  • Numeric/Indexed Array − An array with a numeric index. Values are stored and accessed in linear fashion.
  • Associative array − An array with strings as an index. This stores element values in association with key values rather than in a strict linear index order.
  • Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices.

Numeric/Indexed Array

An indexed or numeric array stores each array element with a numeric index.

$fruit = array("Mango", "Papaya", "Orange");
echo "I would like to eat " . $fruit[0] . ", " . $fruit[1] . " and " . $fruit[2] . "."; 

Run : http://ideone.com/OuXU3A

[tc_output_window] I would like to eat Mango, Papaya and Orange. [/tc_output_window]

Associative Arrays

The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.

$age = array("Symntha"=>"15", "Clan"=>"17", "Smith"=>"23");
echo "Symntha is " . $age['Symntha'] . " years old.";

Run : http://ideone.com/BFRnAf

[tc_output_window] Symntha is 15 years old. [/tc_output_window]

Multi-dimensional Array

A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

$cars = array
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".\n";
echo "<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".\n";

Run : http://ideone.com/0o2e9P

[tc_output_window] Elentra: In stock: 22, sold: 18. Audi: In stock: 15, sold: 13. [/tc_output_window]