PHP Exercises: Deep flatten an given array

PHP: Exercise-79 with Solution

Write a PHP program to deep flatten an given array.

Sample Solution:

PHP Code:

// Function definition for 'deep_flatten' that takes an array of items as a parameter
function deep_flatten($items)
    // Initialize an empty array to store the flattened result
    $result = [];

    // Iterate through each item in the array
    foreach ($items as $item) {
        // Check if the current item is not an array
        if (!is_array($item)) {
            // If not an array, add the item to the result array
            $result[] = $item;
        } else {
            // If the current item is an array, recursively call 'deep_flatten' on the item and merge the result with the current result array
            $result = array_merge($result, deep_flatten($item));

    // Return the flattened result array
    return $result;

// Call 'deep_flatten' with a nested array as a parameter and assign the result to the variable '$result'
$result = deep_flatten([1, [2], [[3], 4], 5, 6]); 

// Display the result using 'print_r'

Sample Output:

    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6


Flowchart: Deep flatten an given array.

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP program to create a function that returns true for all elements of an array, false otherwise.
Next: Write a PHP program to create a new array with n elements removed from the left.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.