Skip to content

array_flatten

Tonya Mork edited this page Dec 11, 2017 · 5 revisions

The array_flatten() function flattens a multi-dimensional array into a single level (depth). By default, the entire array, meaning all depths, are flattened. However, you can specify the number of depths.

Note: The keys are not preserved in the flattened level.

Syntax

array array_flatten(
   array $subjectArray, 
   int $depth = INF
);

where,

$subjectArray is the array to work on

$depth is the depth to flatten, meaning the number of levels within the $subjectArray to flatten. It defaults to infinite, meaning the entire array.

Example

For the given array:

$user = [
    'user_id' => 504,
    'name'    => 'Bob Jones',
    'social'  => [
        'twitter' => '@bobjones',
        'website' => [
            'personal' => 'https://bobjones.com',
            'business' => 'https://example.com',
        ],
    ],
];

With no delimiter specified, you would get:

$user = array_flatten($user);

// $user = [504, 'Bob Jones', '@bobjones'];

If you wanted a depth of 1, you would get:

$user = array_flatten($user, 1);

/**
$user = [
    504,
    'Bob Jones',
    '@bobjones',
    [
        'personal' => 'https://bobjones.com',
        'business' => 'https://foo.com',
    ],
];
*/
Clone this wiki locally