PHP – Flatten or Merge a Multidimensional Array

Here’s a code snippet to flatten or merge a multidimensional array. This is useful when we need to find if a value exists in any of the nodes in a multidimensional array.

I use this function in my Paid Content Packages WordPress Plugin to find out if any of the packages have any page or post assigned.

PHP Function:

function flattenArray($arrayToFlatten) {

	$flatArray = array();

	foreach($arrayToFlatten as $element) {
		if (is_array($element)) {
			$flatArray = array_merge($flatArray, flattenArray($element));
		} else {
			$flatArray[] = $element;
		}
	}

	return $flatArray;
}

Example:

$array = array(
	'parent-one' => 'parent-one',
	'parent-two' => 'parent-two',
	'parent-three' => array(
		'child-one' => 'child-one',
		'child-two' => 'child-two',
		'child-three' => array(
			'kid-one' => 'kid-one',
			'kid-two' => 'kid-two',
		),
	),
);
print_r(flattenArray($array));

This code will print the following output.

Array
(
    [0] => parent-one
    [1] => parent-two
    [2] => child-one
    [3] => child-two
    [4] => kid-one
    [5] => kid-two
)
contact us

There are shorter versions of this function available, however, I like to use code that is clear and easy to read. Hope this helps you if you are finding a solution to this.

Our Services

Enquiry Now

When We Work Together

We can create something incredible

arrow
HQ INDIA
HQ INDIA
C-31, Milap Nagar,
Uttam Nagar, New Delhi,
Delhi 110059
USA
USA
6715 Backlick Rd Suite 202
Springfield,
VA 22150, USA
AUSTRALIA
AUSTRALIA
2/51, Lane Cres,
Reservoir, VIC
3037, Australia
CANADA
CANADA
61 Payzant Bog Road, Falmouth, NS, B0P 1P0, CANADA
UK
UK
3rd Floor, 131 City Road, London, EC1V 2NX, United Kingdom
UAE
UAE
Boutik Mall, Al Reem Island - Abu Dhabi, UAE
X

Let Us Call You Back

  • India+91
  • United States+1
  • United Arab Emirates+971

Your phone number is kept confidential
and not shared with others.