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 :

Tutorials Class - Output Window

I would like to eat Mango, Papaya and Orange.

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 :

Tutorials Class - Output Window

Symntha is 15 years old.

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 :

Tutorials Class - Output Window

Elentra: In stock: 22, sold: 18.
Audi: In stock: 15, sold: 13.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Remove specific element by value from an array in PHP?
PHP Array to String Conversion (favourite colours chosen by user)
How to check if an array is a subset of another in PHP?
Interview Questions & Answers
No Content Found.