⊗ppPmRcMA 220 of 447 menu

Recursion and Multidimensional Structures in PHP

Given is a multidimensional array of arbitrary nesting level, for example, like this:

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

As you can see, this array has a complex structure, and it is assumed that this structure can be arbitrary and the nesting levels can be as deep as desired.

Suppose we want to display all primitive (that is, non-arrays) elements of our array. In this case, to traverse such an array, we simply cannot use loops, because the array has an irregular structure and an unknown level of nesting.

However, recursion will be very convenient for traversing such an array.

First, let's create a function that will take our array as a parameter, and inside the function we will make a loop to traverse our array:

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

The loop we made will only traverse the elements of the main array. That is, first it will output 1, then [2, 7, 8], and then [3, 4, [5, [6, 7]].

Let's now separate primitive elements and array elements in the loop:

<?php function func($arr) { foreach ($arr as $elem) { if (is_array($elem)) { // element is an array } else { // element is a primitive echo $elem; } } } func([1, [2, 7, 8], [3, 4, [5, [6, 7]]]]); ?>

And now let's make it so that if our element is an array, the function calls itself, passing this array as a parameter:

<?php function func($arr) { foreach ($arr as $elem) { if (is_array($elem)) { func($elem); } else { echo $elem; } } } func([1, [2, 7, 8], [3, 4, [5, [6, 7]]]]); ?>

Given a multidimensional array of arbitrary nesting level, for example, like this:

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

Using recursion, display all primitive elements of this array.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline