23 of 110 menu

PHP Multidimensional Array

Multidimensional array is an array whose elements are also arrays.

Here is an example of a two-dimensional array:

<?php $arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; ?>

Here is an example of a three-dimensional array:

<?php $arr = [[[1, 2], [3, 4]], [5, 6]]; ?>

And so on - arrays can have any level of nesting.

How to output an element from a multidimensional array

Let's say we have the following array:

<?php $arr = [ 'boys' => ['John', 'Nick', 'Mike'], 'girls' => ['Mary', 'Natasha', 'Helen'], ]; echo $arr['boys'][0]; ?>

Let's output, for example, 'Nick' using our array:

<?php $arr = [ 'boys' => ['John', 'Nick', 'Mike'], 'girls' => ['Mary', 'Natasha', 'Helen'], ]; echo $arr['boys'][1]; // will output 'Nick' ?>

And now let's output 'Helen':

<?php $arr = [ 'boys' => ['John', 'Nick', 'Mike'], 'girls' => ['Mary', 'Natasha', 'Helen'], ]; echo $arr['girls'][2]; // will output 'Helen' ?>

Array iteration example

Let's say we have an array:

<?php $arr = [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]; ?>

Let's output all its elements to the screen. To do this, we need to run two loops nested within each other:

<?php $arr = [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]; foreach ($arr as $elem) { foreach ($elem as $subElem) { echo $subElem; } } ?>

See Also

English
БеларускаяEspañolРусский
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline