PHP

Flattening a Multidimensional Array

Learn how to convert a nested or multidimensional PHP array into a single-dimensional array, simplifying data access and manipulation for web applications.

<?php
function flattenArray(array $array): array {
    $result = [];
    array_walk_recursive($array, function($value) use (&$result) {
        $result[] = $value;
    });
    return $result;
}

$multiDimensionalArray = [
    'fruits' => ['apple', 'banana'],
    'vegetables' => [
        'leafy' => ['spinach', 'kale'],
        'root' => ['carrot', 'potato']
    ],
    'grains' => 'rice'
];

$flatArray = flattenArray($multiDimensionalArray);
print_r($flatArray);
?>
How it works: This snippet provides a custom function `flattenArray` that takes a multidimensional array and returns a single-dimensional array. It uses `array_walk_recursive`, which applies a user-defined function to every member of an array, including sub-arrays. The anonymous function captures the `$result` array by reference, pushing each value encountered during the recursive walk into it, effectively flattening the structure.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs