Php create multidimensional array in loop

I am trying to create a multidimensional array in PHP using a foreach loop. Here is the code thus far:

$levels = array('low', 'medium', 'high');
$attributes = array('fat', 'quantity', 'ratio', 'label');

foreach ($levels as $key => $level):
       foreach ($attributes as $k =>$attribute):
             $variables[] = $attribute . '_' . $level;
       endforeach;
endforeach;

echo '<pre>' . print_r($levels,1) . '</pre>';   
echo '<pre>' . print_r($variables,1) . '</pre>';    

The output from this code is a single dimension array; however, that is not the intent. The desired array should look like this:

Php create multidimensional array in loop

How should the code be modified to achieve the goal?

asked Aug 8, 2013 at 20:39

1

You're aaalmost there. Just add the level to the array creation :)

$levels = array('low', 'medium', 'high');
$attributes = array('fat', 'quantity', 'ratio', 'label');

foreach ($levels as $key => $level):
       foreach ($attributes as $k =>$attribute):
             $variables[$level][] = $attribute . '_' . $level; // changed $variables[] to $variables[$level][]
       endforeach;
endforeach;

echo '<pre>' . print_r($levels,1) . '</pre>';   
echo '<pre>' . print_r($variables,1) . '</pre>';  

Output

Array
(
    [low] => Array
        (
            [0] => fat_low
            [1] => quantity_low
            [2] => ratio_low
            [3] => label_low
        )

    [medium] => Array
        (
            [0] => fat_medium
            [1] => quantity_medium
            [2] => ratio_medium
            [3] => label_medium
        )

    [high] => Array
        (
            [0] => fat_high
            [1] => quantity_high
            [2] => ratio_high
            [3] => label_high
        )

)

answered Aug 8, 2013 at 20:42

JimLJimL

2,4711 gold badge18 silver badges19 bronze badges

1

$levels = ['low', 'medium', 'high'];
$attributes = ['fat', 'quantity', 'ratio', 'label'];

$result = [];
foreach ($levels as $level) {
    $result[$level] = [];
    foreach ($attributes as $attribute) {
        $result[$level][] = $attribute . '_' . $level;
    }
}

var_dump($result);

answered Aug 8, 2013 at 20:44

Php create multidimensional array in loop

Tomasz KowalczykTomasz Kowalczyk

10.4k6 gold badges54 silver badges66 bronze badges

4

$levels = array('low', 'medium', 'high');
$attributes = array('fat', 'quantity', 'ratio', 'label');

foreach ($levels as $key => $level){
    foreach ($attributes as $k =>$attribute){
             $variables[$level][] = $attribute . '_' . $level;
   }
}

print_r($variables);

http://codepad.viper-7.com/xlvZ2W

answered Aug 8, 2013 at 20:46


In the previous pages, we have described arrays that are a single list of key/value pairs.

However, sometimes you want to store values with more than one key. For this, we have multidimensional arrays.


PHP - Multidimensional Arrays

A multidimensional array is an array containing one or more arrays.

PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.

The dimension of an array indicates the number of indices you need to select an element.

  • For a two-dimensional array you need two indices to select an element
  • For a three-dimensional array you need three indices to select an element


PHP - Two-dimensional Arrays

A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).

First, take a look at the following table:

NameStockSold
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15

We can store the data from the table above in a two-dimensional array, like this:

$cars = array (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
);

Now the two-dimensional $cars array contains four arrays, and it has two indices: row and column.

To get access to the elements of the $cars array we must point to the two indices (row and column):

Example

<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>

Try it Yourself »

We can also put a for loop inside another for loop to get the elements of the $cars array (we still have to point to the two indices):

Example

<?php
for ($row = 0; $row < 4; $row++) {
  echo "<p><b>Row number $row</b></p>";
  echo "<ul>";
  for ($col = 0; $col < 3; $col++) {
    echo "<li>".$cars[$row][$col]."</li>";
  }
  echo "</ul>";
}
?>

Try it Yourself »


Complete PHP Array Reference

For a complete reference of all array functions, go to our complete PHP Array Reference.

The reference contains a brief description, and examples of use, for each function!



How do you loop through a multidimensional array in PHP?

Looping through multidimensional arrays Just as with regular, single-dimensional arrays, you can use foreach to loop through multidimensional arrays. To do this, you need to create nested foreach loops — that is, one loop inside another: The outer loop reads each element in the top-level array.

How to define multiple array in PHP?

PHP - Multidimensional Arrays.
For a two-dimensional array you need two indices to select an element..
For a three-dimensional array you need three indices to select an element..

How can we store multidimensional array in database using PHP?

PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an array. PHP multidimensional array can be represented in the form of matrix which is represented by row * column. ... PHP Multidimensional Array Example..

What is multidimensional array example?

A multi-dimensional array is an array with more than one level or dimension. For example, a 2D array, or two-dimensional array, is an array of arrays, meaning it is a matrix of rows and columns (think of a table). A 3D array adds another dimension, turning it into an array of arrays of arrays.