Skip to content

Instantly share code, notes, and snippets.

@aaronsummers
Created June 10, 2022 12:21
Show Gist options
  • Save aaronsummers/4a971298ee78aaea3b4d34ffb4a246ec to your computer and use it in GitHub Desktop.
Save aaronsummers/4a971298ee78aaea3b4d34ffb4a246ec to your computer and use it in GitHub Desktop.
Flatten Multidimentional Arrays in PHP
<?php
function array_flatten($arrays) {
if ( !is_array($arrays) )
{
return false;
}
$result = array();
foreach ( $arrays as $key => $value )
{
if ( is_array($value) )
{
$result = array_merge( $result, array_flatten($value) );
}
else
{
$result[$key] = $value;
}
}
return $result;
}
// Example
$array = array(
'a' => 'letter',
'b' => array(
'b1' => 'bb',
'b2' => 'bb',
'b3' => array(
'bb1' => 'bbb'
)
)
);
// array_flatten($array)
echo '<pre>' . var_export(array_flatten($array), true) . '</pre>';
// Return
array (
'a' => 'letter',
'b1' => 'bb',
'b2' => 'bb',
'bb1' => 'bbb',
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment