1. php
  2. /arrays

PHP Arrays

A PHP array is a data structure that allows you to store multiple values in a single variable. You can think of an array as a list of items, where each item has an assigned index that you can use to access it.

There are three types of arrays in PHP:

Indexed Arrays

Associative Aarrays

Multidimensional Arrays

Indexed Arrays

An indexed array is a simple array that stores each element with a numeric index, starting from 0. For example, the following code creates an indexed array containing three elements:

$fruits = array("apple", "orange", "banana");

To access an element in an indexed array, you can use the array's name followed by the index of the element in square brackets. For example, to access the first element of the $fruits array, you would use the following code:

echo $fruits[0]; 
// Outputs "apple"

Associative Arrays

An associative array, on the other hand, allows you to store each element with a key that you can use to access it. For example, the following code creates an associative array that maps the names of fruits to their colors:

$fruits = array(
	"apple" => "red", 
	"orange" => "orange", 
	"banana" => "yellow"
	);

To access an element in an associative array, you can use the array's name followed by the key of the element in square brackets. For example, to access the color of the "apple" element in the $fruits array, you would use the following code:

echo $fruits["apple"]; 
// Outputs "red"

Multidimensional arrays

PHP also supports multidimensional arrays, which are arrays that contain other arrays as elements. For example, the following code creates a multidimensional array that contains two indexed arrays:

$fruits = array(
	"red" => array("apple", "strawberry"), 
	"yellow" => array("banana")
	);

To access an element in a multidimensional array, you can use multiple sets of square brackets, with each set corresponding to a level in the array. For example, to access the first element of the "red" array in the $fruits array, you would use the following code:

echo $fruits["red"][0]; 
// Outputs "apple"