Convert multidimensional array in a single array

TechnologyNo Comments

You Are Here:Convert multidimensional array in a single array

PHP or hypertext pre-processor. A server side scripting language. In current scenario PHP is a most used open source programming language. Many frameworks like codeigniter, Zend etc are based on it. According to trusted sources PHP is used by 82.7% of all the websites.

I am also one of them who prefer PHP as a server side scripting language not just because it is simple and easy to understand but for two main things:

  • It has a lot of in built functions that helps a lot is doing programming faster, smoother and effortlessly.
  • Second is the community support it provides. Websites like Stackoverflow and W3Cschool provides solution to almost all the issues which come across in any web developers career.

I have 10 years of experience in web development. I personally felled and experienced this language. I already told the plus points of this language. But as there are good things exists bad thing also exists in between.

Two days back I came across a problem where I have a multi-dimensional array with array in array situation and I have a need to convert it in a single array. I searched a lot to find any pre built function that does this for me and save my time but I failed. After a lot of research, I came to know that there is no pre-built function available to solve this issue. Then I decided to create a short function which will solve this issue easily. Please refer this function if you are also looking for the same. 

Problem:

Multi-dimensional array (array in array situation) to be converted in a single dimensional array.

Array
(
[0] => 9
[1] => Array
(
[0] => 4
[1] => 2
[2] => 3
[3] => Array
(
[0] => 10
[1] => 11
[2] => 12
)

)

[2] => 8
[3] => 1
[4] => Array
(
[0] => 5
[1] => 7
[2] => 6
)

)

Solution:

function single_array($arr){
foreach($arr as $key){
if(is_array($key)){
$arr1=single_array($key);
foreach($arr1 as $k){
$new_arr[]=$k;
}
}
else{
$new_arr[]=$key;
}
}
return $new_arr;
}
//calling
$arr1=single_array($arr);

Output:

Array
(
[0] => 9
[1] => 4
[2] => 2
[3] => 3
[4] => 10
[5] => 11
[6] => 12
[7] => 8
[8] => 1
[9] => 5
[10] => 7
[11] => 6
)

Description:

I created a function called single_array($arr) containing multi-dimensional array as argument. Function checks by iterating in loop each element if that element contains an array single_array($arr) will be called recursively and if element is not an array then it will be stored in a local variable $new_arr and it will be returned when loop ends.

About the author:

Leave a Reply

Your email address will not be published. Required fields are marked *

Top