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:
<?php
// 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'
print_r($result);
?>
Explanation:
- Define deep_flatten Function:
- The deep_flatten function takes an array, potentially containing nested arrays, and returns a single, flat array with all elements.
- Initialize an Empty Array:
- An empty array $result is created to store the flattened elements.
- Iterate Through Each Item in the Array:
- Uses a foreach loop to iterate over each item in $items.
- Check if an Item is Not an Array:
- If an item is not an array, it is appended to $result directly.
- Recursively Flatten Nested Arrays:
- If an item is an array, deep_flatten calls itself recursively on that item.
- Uses array_merge to add the flattened result of this nested array to $result.
- Return Flattened Array:
- Once all items are processed, the fully flattened array $result is returned.
- Call deep_flatten and Display Result:
- deep_flatten is called with [1, [2], [[3], 4], 5, 6], resulting in [1, 2, 3, 4, 5, 6].
- print_r outputs the final flattened array to the screen.
Output:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
Flowchart:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/php-exercises/php-basic-exercise-79.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics