← Back to all snippets
PHP

Flattening a Multi-dimensional PHP Array

Discover techniques to flatten nested PHP arrays into a single-dimensional array, simplifying data processing and iteration.

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

function flattenArray($array) {
    $result = [];
    foreach ($array as $element) {
        if (is_array($element)) {
            $result = array_merge($result, flattenArray($element));
        } else {
            $result[] = $element;
        }
    }
    return $result;
}

$flatArray = flattenArray($nestedArray);
print_r($flatArray);
?>
How it works: This code defines a recursive function `flattenArray()` that takes a multi-dimensional array and returns a single-dimensional array. It iterates through each element; if an element is an array, it recursively calls itself and merges the results. Otherwise, it adds the element directly to the result array, 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