Multidimensional Arrays In PHP
Hey Guys,
In this tutorial, you are going to learn about creating and using Multidimensional Arrays in PHP programming language.
What are Multidimensional Arrays:
Multidimensional Array is a type of array where one array stores other arrays as arguments.
It can be simply explained that to store multiple arrays and access them easily we use the concept of Multidimensional Array.
In our day to day life, we have to deal with situations where you want to store values with more than one key in such cases Multidimensional Array is the best solution.
Creation of Multidimensional Array in PHP:
Creation of Multidimensional Array is similar to Normal Array in place of passing the values we pass arrays as parameters. Let’s learn the process…
Here we create a variable to store array and then pass our sub arrays as parameters.
It can be used in solving matrixes related problems in Mathematics.
$variable_name= array( array(array1), array(array2), ..) ;
Accessing the elements in a Multidimensional Array:
To access the elements in multidimensional arrays in PHP we echo the variable name followed by the index of the element as parameters.
The index numbers start from 00 to nn here the first number is its index in row then columns.
// a 3*3 matrix to give detailed explanation about the index 00 01 02 10 11 12 20 21 22
Syntax:
echo variable_name( row_index, column_index );
Example:
Let us assume we have some bikes and we have to print the cost of bikes beside their name.
Then the PHP code to do so will be as follows that you can see below:
<?php //initializing variable $bikes = array ( array("Honda",60000), array("Bajaj",80000), array("Yamaha",100000), ); //printing the array echo $bikes[0][0].": cost: ".$bikes[0][1]."<br>"; echo $bikes[1][0].": cost: ".$bikes[1][1]."<br>"; echo $bikes[2][0].": cost: ".$bikes[2][1]."<br>"; ?>
Output:
The output of our PHP is just like you can see below:
Honda:cost: 60000 Bajaj: cost: 80000 Yamaha: cost: 100000
Also, read:
Leave a Reply