What is PHP Multi Array | PHP Multidimensional Array ?

PHP Multi Array
A PHP multi-array is an array that contains one or more than one arrays. PHP multidimensional array that are two, three, four, five, six, seven, eight or more levels deep.
therefore, arrays more then deep are very hard to manage for most peoples. sometimes you have to need store values then one key, for this, we have multidimensional arrays (PHP multi-array)

PHP 2 Dimensional Array

PHP 2 Dimensional Array is an array of arrays, such as for three-dimensional array is an array of arrays array of arrays. first of all, take at the following given table:

Desktop Name In Stock total Sold
Acer 51 25
Dell 45 22
Apple 25 15
Samsung 35 18
Sony 30 12

As per above the given table, we store the data in a PHP 2 dimensional array such as:

$desktops = array
  (
  array("Acer",51,25),
  array("Dell",45,22),
  array("Apple",25,15),
  array("Samsung",35,18),
  array("Sony",30,12)
  );

therefore, $desktops array, the two-dimensional array contains four arrays, and it has two indices row and column, for access the elements of the $desktops array, here we must point to the two indices such as row and column.

<?php
$desktops = array
  (
  array("Acer",51,25),
  array("Dell",45,22),
  array("Apple",25,15),
  array("Samsung",35,18),
  array("Sony",30,12)
  );
  
echo $desktops[0][0].": In stock: ".$desktops[0][1].", Total sold: ".$desktops[0][2].".<br>";
echo $desktops[1][0].": In stock: ".$desktops[1][1].", Total sold: ".$desktops[1][2].".<br>";
echo $desktops[2][0].": In stock: ".$desktops[2][1].", Total sold: ".$desktops[2][2].".<br>";
echo $desktops[3][0].": In stock: ".$desktops[3][1].", Total sold: ".$desktops[3][2].".<br>";
echo $desktops[4][0].": In stock: ".$desktops[4][1].", Total sold: ".$desktops[4][2].".<br>";
?>

furthermore, here we can apply another method to get the elements of the $desktop array, such as we can put a for loop inside another for loop.(here we still have to point to the two indices such as row and column).

<?php
$desktops = array
  (
  array("Acer",51,25),
  array("Dell",45,22),
  array("Apple",25,15),
  array("Samsung",35,18),
  array("Sony",30,12)
  );
for ($row = 0; $row < 5; $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>";
}
?>

Another PHP 2 Dimensional Array Example

<?php 
// Create PHP Program  
// Multidimensional Array 
// Creating multidimensional Array
$profile = array( 
    // Default key for each will 
    // start from 0 
    array("Ashish", "Parul", "Ritu"), 
    array("Madhya Pradesh", "Uttar Pradesh", "Rajasthan") 
); 
// Display the array information Details 
print_r($profile); 
?>

Array
(
    [0] => Array
        (
            [0] => Ashish
            [1] => Parul
            [2] => Ritu
        )

    [1] => Array
        (
            [0] => Madhya Pradesh
            [1] => Uttar Pradesh
            [2] => Rajasthan
        )

)

Three Dimensional Array:

It also comes in a multidimensional array, Initialization in Three Dimensional array is works same as the PHP 2 dimensional Arrays. therefore the differences come in the number of dimensions increases so the number of nested braces will also increase, let’s see the example.

<?php 
// Creating three Dimensional Array 
// Create three nested array 
$example = array( 
    array( 
        array(11, 12), 
        array(13, 14), 
    ), 
    array( 
        array(15, 16), 
        array(17, 18), 
    ), 
); 
// Display the result information 
print_r($example); 
?>

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => 11
                    [1] => 12
                )

            [1] => Array
                (
                    [0] => 13
                    [1] => 14
                )
       )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => 15
                    [1] => 16
                )

            [1] => Array
                (
                    [0] => 17
                    [1] => 18
                )
         )
)

Accessing Multidimensional Array Elements

To accessing the (PHP Multi-Array) multidimensional array element in PHP, there are mainly two ways such as:
For access Elements using dimension as array_name [‘first-dimension’] [‘second-dimension’] Elements can be accessed using the for loop method.
the Elements can be accessed using for each loop method.

<?php 
// Create PHp Multidimensional Array 
// Creating Multidimensional Associative Array 
$marks = array( 
	"Shyam" => array( 
		"maths" => 90, 
		"physics" => 75, 
		"chemistry" => 84, 
	), 
	"Sita" => array( 
		"maths" => 82, 
		"physics" => 88, 
		"chemistry" => 96, 
	), 
	"Kuldeep" => array(  
		"maths" => 89, 
		"physics" => 86, 
		"chemistry" => 87, 
	), 
); 

// Accessing the array element using dimensions 
// It will display the marks of 
// Shyam in Maths subject 
echo $marks['Shyam']['maths'] . "\n"; 
	
// Accessing array elements using for each loop 
foreach($marks as $mark) { 
	echo $mark['maths']. " ".$mark['physics']." ".$mark['chemistry']."\n"; 
} 
?>

90
90 75 84
82 88 96
89 86 87

Traversing Multidimensional Arrays

Traversing an array means to iterate it starting from the first index to the last element of the array, therefore, we can traverse a multidimensional array either using one for loop or one foreach or two foreach or two for loops. furthermore, to know the basic usage and syntax of foreach and for a loop.

therefore, below we show how some of these can be applied to multidimensional arrays (PHP multi-array). here, first, we present array_walk_recursive function for traversing multidimensional arrays.

PHP Multi Array | array_walk_recursive

the array_walk_recursive function iterates over the elements of a multidimensional array applying the callback function passed as the second argument to each element of sub-arrays. only the elements which are not themselves arrays are passed to the callback function.
To demonstrate the multi-level array, we apply array_walk_recursive, the inline callback function applies the ucwords string function to each value passed.

<?php
$food_name = [
    'meat' => ['mutton', 'chickens'],
    'vegetables' => [
        'leaf' => ['Gotukola', 'Swiss chard', 'water spinach', 'Sabzi Khordan', 'lettuce'],
        'root' => ['potatoes', 'carrots', 'onions', 'garlic'],
        'other' => ['cauliflower', 'tumeric', 'ginger', 'jicama']
    ],
    'grains' => ['wheat', 'popcorn', 'oatmeal'],
];

array_walk_recursive($food_name, function (&$val) { $val = ucwords($val); } );
print_r($food_name);
?>

Array
(
    [meat] => Array
        (
            [0] => mutton
            [1] => chikens
        )

    [vegetables] => Array
        (
            [leaf] => Array
                (
                    [0] => Gotukola
                    [1] => Swiss chard
                    [2] => water spinach
                    [3] => Sabzi Khordan
                    [4] => lettuce
                )

            [root] => Array
                (
                    [0] => potatoes
                    [1] => carrots
                    [2] => onions
                    [3] => garlic
                )

            [other] => Array
                (
                    [0] => cauliflower
                    [1] => tumeric
                    [2] => ginger
                    [3] => jicama
                )
        )

    [grains] => Array
        (
            [0] => Wheat
            [1] => popcorn
            [2] => oatmeal
        )
)

Using foreach to Traverse Multidimensional Arrays

There are the number of methods or ways that you could use foreach and for loops to iterate over multidimensional arrays. I will show you an example of these possibilities here.

therefore, we lool first example combines foreach which list to display values from each sub-array.

$products = [
    // label, name, total price
    ['espresso_Cake', 'espresso Cake', 215],
    ['avocado_Cake', 'avocado Cake', 220],
    ['mayo_Cake', 'mayo Cake', 230],
    ['craving_Cake', 'craving Cake', 194]
];

foreach($products as $product) {
    //list($label, $name, $price) = $product;
    list(, $name, $price) = $product; // to discard label
    echo "$name is \$$price.<br />";
}
/* 
espresso Cake is $215.
avocado Cake is $220.
mayo Cake is $230.
mraving Cake is $194. 
*/

The next example produces the same result by applying extract to associative sub-arrays:

$products2 = [
    ['label' => 'espresso_Cake', 'name' => 'espresso Cake', 'price' => 215],
    ['label' => 'avocado_Cake', 'name' => 'avocado Cake', 'price' => 220],
    ['label' => 'mayo_Cake', 'name' => 'mayo Cake', 'price' => 230],
    ['label' => 'craving_Cake', 'name' => 'craving Cake', 'price' => 194]
];

foreach($products2 as $product) {
    extract($product);
    echo "$name is \$$price.<br />";
}
// (The result will come as above example)

furthermore, the following example modifies the array, achieving the same result as array_walk_recursive in an earlier example:

$products = [
    ['espresso_Cake', 'espresso Cake', 215],
    ['avocado_Cake', 'avocado Cake', 220],
    ['mayo_Cake', 'mayo Cake', 230],
    ['craving_Cake', 'craving Cake', 194]
];

// use & (reference sign) to change values in array
foreach($products as &$product) {
    $product[2] *= 1.1; // 
}
print_r($products);
/* Array
(
    [0] => Array
        (
            [0] => espresso_Cake
            [1] => espresso_Cake
            [2] => 236.5
        )

    [1] => Array
        (
            [0] => carrot_cake
            [1] => avocado Cake
            [2] => 242
        )

    [2] => Array
        (
            [0] => mayo_Cake
            [1] => mayo Cake
            [2] => 253
        )

    [3] => Array
        (
            [0] => craving_Cake
            [1] => craving Cake
            [2] => 213.4
        )

) */

Using one for loop and one foreach (In PHP Multi Array)

In the case PHP multi-array we have to traverse the main array and then these arrays stored inside the main arrays, such in this case we need two loops.
First all, while we are using for loop to traverse a multidimensional array we must know the length/size of the array, the length/size we can be found using the count() function.
lets us see the given following example of traversing the multidimensional array.

<?php
/* 
    multidimensional array initialization
*/
$cars = array(
    array(
        "name"=>"Hyundai", 
        "type"=>"Hyundai Motor", 
        "brand"=>"WRC"
    ),
    array(
        "name"=>"Hyundai", 
        "type"=>"Hyundai Motor", 
        "brand"=>"Genesis"
    ),
    array(
        "name"=>"Hyundai", 
        "type"=>"Hyundai Motor", 
        "brand"=>"Sonata"
    ),
);

// array traversal to find size of the array
$size = count($WRC);

// using the for loop
for($i = 0; $i < $size; $i++)
{
    foreach($cars[$i] as $key => $value) {
        echo $key . " : " . $value . "\n";
    }
    echo "\n";
}
?>

we have the main array as an indexed array and the arrays stored as elements associative, but the main array can also be associative, let’s see the example for it.

therefore, in PHP multi-array as the index in the associative array is not sequentially and not numeric, thus to find the index values or keys (as the data saved in associative array in the form of key-value), therefore, here, in this case, we can use the function array_keys() to get an array of the keys used in the associative array.

<?php
/* 
    multidimensional array initialization
*/
$cars = array(
    "Bentayga" => array(
            "type"=>"SUV", 
            "brand"=>"Bentley"
        ),
    "Cayenne" => array(
            "type"=>"SUV", 
            "brand"=>"Porsche"
        ),
    "Urus" => array(
            "type"=>"SUV", 
            "brand"=>"Lamborghini"
        ),
    
);

/* 
    array traversal
*/
// find size of the array
$size = count($Bentley);

// array keys
$keys = arra_keys($cars);

// using the for loop
for($i = 0; $i < $size; $i++)
{
    echo $keys[$i]. "\n";
    foreach($cars[$keys[$i]] as $key => $value) {
        echo $key . " : " . $value . "\n";
    }
    echo "\n";
}

?>

 

Advantages of PHP Multi Array

There are advantages of using a multidimensional array:

We can be stored Detailed information in a multidimensional array.
On the top level, it can either be kept associative or indexed, which makes it user-friendly, as they can use it as per their requirements.

Summary : Remember Points

The array variable which the capacity to store multi values.
as you see, the Numeric arrays use numbers for the array keys.
therefore, Associative array (it is a part of the multidimensional array) use descriptive names for array keys
Multidimensional arrays contain other arrays inside them.
The count function, as you see it is used to get the number of items that have been stored in an array.