How to work with arrays of arrays (nested arrays/two-dimensional array)
Code that creates an array of arrays
$times_table = array(); // create an empty array
for ($i = 0; $i <= 12; $i++) {
for ($j = 0; $j <= 12; $j++) {
$times_table[$i][$j] = $i * $j;
}
}
Code that adds values to the array of arrays
for ($i = 0; $i <= 12; $i++) {
for ($j = 0; $j <= 12; $j++) {
$times_table[$i][$j] = $i * $j;
}
}
Code that refers to elements in the array of arrays
echo $times_table[4][3];
echo $times_table[7][6];
\$times_table[4][3] = " . $times_table[4][3] . "
\n");
echo("\$times_table[7][6] = " . $times_table[7][6] . "\n");
?>
Code that creates a cart array
$cart = array();
$item['itemCode'] = 123;
$item['itemName'] = 'Visual Basic';
$item['itemCost'] = 57.5;
$item['itemQuantity'] = 5;
$cart[] = $item;
$item['itemCode'] = 456;
$item['itemName'] = 'Java';
$item['itemCost'] = 59.5;
$item['itemQuantity'] = 2;
$cart[] = $item; // add item array to cart array
\$cart = ");
print_r($cart);
echo("\n");
?>
Code that creates and adds another associative array to the cart array
$item = array(); // create an empty item array
Code that refers to the elements in the array of associative arrays
echo $cart[0]['itemCode']; // displays 123
echo $cart[1]['itemName']; // displays Java
\$cart[0]['itemcode'] = " . $cart[0]['itemCode']); // displays 123
echo("
\n\$cart[1]['itemcode'] = " . $cart[1]['itemName'] . "\n"); // displays Java
?>
A more concise way to create an array of arrays
$cart = array(
array('itemCode' => 123, 'itemName' => 'Visual Basic', 'itemCost' => 57.5, 'itemQuantity' => 5),
array('itemCode' => 456, 'itemName' => 'Java', 'itemCost' => 59.5, 'itemQuantity' => 2)
);
- To refer to the elements in an array of arrays, you use two index values for each element. The first index is for an element in the outer array. The second index is for an element in the inner array.
Back