Show List

PHP Arrays

In PHP, an array is a data structure that allows you to store multiple values in a single variable. There are three types of arrays in PHP: indexed, associative, and multidimensional.

1. Indexed Arrays

An indexed array is a type of array where the keys are numerical indices. The first element of the array has an index of 0, the second has an index of 1, and so on. Here's an example of an indexed array:

php
Copy code
$colors = array("Red", "Green", "Blue");

In the above example, $colors is an indexed array with three elements. You can access each element of the array using its index, like this:

php
Copy code
echo $colors[0]; // Output: Red echo $colors[1]; // Output: Green echo $colors[2]; // Output: Blue

2. Associative Arrays

An associative array is a type of array where the keys are strings instead of numerical indices. Each key in the array is associated with a value. Here's an example of an associative array:

php
Copy code
$person = array("name" => "John", "age" => 30, "city" => "New York");

In the above example, $person is an associative array with three elements. You can access each element of the array using its key, like this:

php
Copy code
echo $person["name"]; // Output: John echo $person["age"]; // Output: 30 echo $person["city"]; // Output: New York

3. Multi-dimensional Arrays

A multidimensional array is an array that contains one or more arrays as its elements. Each element in the outer array can be another array, creating a hierarchical structure. Here's an example of a multidimensional array:

php
Copy code
$students = array( array("name" => "John", "age" => 20, "city" => "New York"), array("name" => "Mary", "age" => 25, "city" => "Los Angeles"), array("name" => "Bob", "age" => 22, "city" => "Chicago") );

In the above example, $students is a multidimensional array with three elements, each of which is an associative array. You can access each element of the array using its indices, like this:

php
Copy code
echo $students[0]["name"]; // Output: John echo $students[1]["age"]; // Output: 25 echo $students[2]["city"]; // Output: Chicago

    Leave a Comment


  • captcha text