How to make a PHP array of array

Learn how to sort an array in PHP with a simple example. Understand how to use sort() & usort() to organize & rearrange your data.

Creating a PHP Array of Arrays

An array of arrays is a data structure in which an array holds other arrays as its elements. It is useful for grouping related data together and accessing it in a convenient and efficient way. In PHP, you can create an array of arrays with the array() function.

To demonstrate, let's create an array that contains information about a few cities:

$cities = array(
    array("name" => "Paris", "country" => "France", "population" => 2.141),
    array("name" => "New York", "country" => "USA", "population" => 8.623),
    array("name" => "Tokyo", "country" => "Japan", "population" => 13.929)

This array contains three elements, each of which is an array that holds information about a city. If we want to access one of these elements, we can use array notation to do so:

echo $cities[0]["name"]; // Outputs "Paris"
echo $cities[1]["country"]; // Outputs "USA"
echo $cities[2]["population"]; // Outputs "13.929"

We can also loop through the array of arrays to access each element:

foreach ($cities as $city) {
    echo $city["name"] . ", " . $city["country"] . " (" . $city["population"] . ")";

// Outputs:
// Paris, France (2.141)
// New York, USA (8.623)
// Tokyo, Japan (13.929)

As you can see, an array of arrays is an easy and efficient way to group related data together and access it in a convenient way. From storing lists of products to organizing information about users, this data structure can be useful in a variety of situations.

Answers (0)