The following article shows some Examples of 2D Indexed Arrays in PHP.
- Example with numerical indices. The following example shows a 2D indexed array with dimension 2X2.
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
- Example with string indices. The following example shows the use of string indices.
$table = array(
array("name" => "John", "age" => 25, "city" => "New York"),
array("name" => "Mary", "age" => 30, "city" => "London"),
array("name" => "Bob", "age" => 20, "city" => "Paris")
);
- Example with mixed indices. The following example shows the use of mixed indices.
$items = array(
array("item_id" => 1, "name" => "Apple", "price" => 1.5),
array("item_id" => 2, "name" => "Banana", "price" => 2.0),
array("item_id" => 3, "name" => "Orange", "price" => 1.0)
);
- Example with dynamic indices.
$grades = array();
$grades[] = array(80, 90, 70);
$grades[] = array(75, 85, 95);
$grades[] = array(60, 65, 70);
- Example with empty 2D array.
$empty_array = array(
array(),
array(),
array()
);
In all these examples, the first index is used to access the row and the second index is used to access the column in the 2D indexed array.
Further Reading
Examples of Array Functions in PHP