How to create a multi dimensional array from indexed array ?

Created at 13-Jul-2023 , By samar

Here we have two different method to create a multi dimensional array from indexed array. You can use foreach loop or you can also use for loop to create a multi dimensional array from an indexed array.

Create a multidimensional array from indexed array using for loop

You have to first Initialize the indexed array. Now you have to sort the array in ascending order and create output array variable to insert the array element from indexed array and after that you have to Iterate over the elements of the indexed array and check if the next key value exists in array using isset then add current key value ($arr[$i]) and next key value ($arr[$i+1]) to output array and increment the key counter by 2 using $i += 2 in for loop.

<?php
$arr = [1, 2, 4, 3, 7, 8, 6, 5, 10, 9,11];

sort($arr); // sort in ascending order

$output = array();

for ($i = 0; $i < count($arr); $i += 2) {
    if (isset($arr[$i+1])) {
        $output[] = array($arr[$i], $arr[$i+1]);
    } else {
        $output[] = array($arr[$i]);
    }
}
echo "<pre>";
print_r($output);

Create a multidimensional array from indexed array using foreach loop

Here you have to use continue statement if modulus of current key in foreach loop is 1 ($key%2 == 1) which stop the execution of current iteration and move to next iteration and check the next key element exists in array then add both element of array to $mutArray array else add the current key element to $mutArray array.

<?php

$array = array(1,2,3,4,5,6,7,8,9,10,11,12,13);

$arrayKey = 0;
$mutArray = array();
foreach($array as $key => $val){
    if($key%2 == 1){
        continue;
    }
    
    if(isset($array[$key+1])){
       $mutArray[] =  array($array[$key], $array[$key+1]);
    }else{
        $mutArray[] = array($array[$key]);
    }
}

echo "<pre>";
print_r($mutArray);

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.