• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / PHP / PHP Arrays / Using Multidimensional Arrays in PHP

Using Multidimensional Arrays in PHP

19 July 2010 / 16 Comments

Using Multidimensional Arrays in PHP

Array elements in PHP can hold values of any type, such as numbers, strings and objects. They can also hold other arrays, which means you can create multidimensional, or nested, arrays.

In this tutorial you learn how to create multidimensional arrays, how to access elements in a multidimensional array, and how to loop through multidimensional arrays.

How to create a multidimensional array

You create a multidimensional array using the array() construct, much like creating a regular array. The difference is that each element in the array you create is itself an array.

For example:


$myArray = array(
  array( value1, value2, value3 ),
  array( value4, value5, value6 ),
  array( value7, value8, value9 )
);

The above example creates a 2-dimensional array. The top-level array contains 3 elements. Each element is itself an array containing 3 values.

You can also use associative arrays in multidimensional arrays. The following example creates an indexed array containing 3 associative arrays:


$movies = array(
  array(
    "title" => "Rear Window",
    "director" => "Alfred Hitchcock",
    "year" => 1954
  ),
  array(
    "title" => "Full Metal Jacket",
    "director" => "Stanley Kubrick",
    "year" => 1987
  ),
  array(
    "title" => "Mean Streets",
    "director" => "Martin Scorsese",
    "year" => 1973
  )
);

You can nest arrays as many levels deep as you like (although it’s rare to go higher than 3 levels). Here’s a 3-dimensional array:


$myArray = array(
  array(
    array( value1, value2 ),
    array( value3, value4 )
  ),
  array(
    array( value5, value6 ),
    array( value7, value8 )
  )
);

Accessing elements in a multidimensional array

To access multidimensional array elements, you can use the same square bracket syntax that you use with regular arrays. If you want to access the second-level array elements in a 2-dimensional array, just use 2 sets of square brackets — for example:


$myArray = array(
  array( "one", "two", "three" ),
  array( "four", "five", "six" )
);

// Displays "six"
echo $myArray[1][2];
?>

Here are some examples that access various elements in the $movies multidimensional array created earlier:


echo "The title of the first movie:<br />";
echo $movies[0]["title"] . "<br /><br />";

echo "The director of the third movie:<br />";
echo $movies[2]["director"] . "<br /><br />";

echo "The nested array contained in the first element:<br />";
print_r( $movies[0] );
echo "<br /><br />";

The above code produces the following output:


The title of the first movie:
Rear Window

The director of the third movie:
Martin Scorsese

The nested array contained in the first element:
Array ( [title] => Rear Window [director] => Alfred Hitchcock [year] => 1954 )

The last example uses $movies[0] to access the entire nested array contained in the first element of the top-level array, then uses print_r() to display the array’s contents. (Find out more about print_r() in Working With Array Elements 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:

  1. The outer loop reads each element in the top-level array.
  2. For each of those top-level elements, the inner loop moves through the array contained in the top-level element, and so on.

Here’s an example that creates a 2-dimensional array of movie information, then loops through the array, displaying the information in the page:


$movies = array(
  array(
    "title" => "Rear Window",
    "director" => "Alfred Hitchcock",
    "year" => 1954
  ),
  array(
    "title" => "Full Metal Jacket",
    "director" => "Stanley Kubrick",
    "year" => 1987
  ),
  array(
    "title" => "Mean Streets",
    "director" => "Martin Scorsese",
    "year" => 1973
  )
);

foreach ( $movies as $movie ) {

  echo '<dl style="margin-bottom: 1em;">';

  foreach ( $movie as $key => $value ) {
    echo "<dt>$key</dt><dd>$value</dd>";
  }

  echo '</dl>';
}

The above script displays the following:


title
    Rear Window
director
    Alfred Hitchcock
year
    1954

title
    Full Metal Jacket
director
    Stanley Kubrick
year
    1987

title
    Mean Streets
director
    Martin Scorsese
year
    1973

Summary

In this tutorial you’ve seen how to create, manipulate, and loop through multidimensional arrays in PHP. Multidimensional arrays are useful for all sorts of things, such as holding multiple database records and storing data to display in tables. Now that you know how to use them, you can add a new level of sophistication to your PHP scripts.

Happy coding!

Filed Under: PHP Arrays Tagged With: accessing elements, creating, foreach, looping through, multidimensional arrays, nested arrays, php

Reader Interactions

Comments

  1. Christian Scholz-Flöter says

    6 May 2019 at 9:36 am

    Thanks for this comprehensive write-up. I tend to forget how arrays are created in PHP. Now, I have this neat article to look it up. 🙂

    Reply
    • Matt Doyle says

      21 May 2019 at 2:26 am

      Thanks Christian! Glad you found the article helpful 🙂

      Reply
  2. toni says

    17 May 2019 at 1:44 pm

    Thanks broo
    Help me to figure “names” as an array index 😀

    Reply
  3. toni says

    17 May 2019 at 1:57 pm

    echo $entries[0][cn][0].””;
    echo $entries[0][description][0].””;
    ldap_get_entries

    Reply
  4. toni says

    17 May 2019 at 1:58 pm

    echo $entries[0][cn][0];
    echo $entries[0][description][0];

    ldap_get_entries

    Reply
  5. Thomas Bishop says

    2 July 2019 at 2:15 pm

    Really good, no-nonsense account. Thank you.

    Reply
    • Matt Doyle says

      13 July 2019 at 3:39 am

      You’re welcome, Thomas. I’m glad it helped 🙂

      Reply
  6. gerald says

    12 September 2019 at 1:05 pm

    hello am i right with this code, because they are not function

        $username_arr = $_POST['username_arr'];
        $name_arr = $_POST['name_arr'];
        $age_arr = $_POST['age_arr'];
        $email_arr = $_POST['email_arr'];
        $salary_arr = $_POST['salary_arr'];
    
        $user_data = array();
    
        // Loop on Array and write your Insert query
        foreach($username_arr as $key=>$username){
            $user_data[] = array("username"=>$username, "name"=>$name_arr[$key],"age"=>$age_arr[$key],"email"=>$email_arr[$key],"salary"=>$salary_arr[$key]);
        
    $queryq = "INSERT INTO users (`id`, `username`, `fname`, `lname`, `email`, `age`, `salary`) VALUES ('', '$username', '$name', '', '$email', '$age', '$salary')";
    
       
        $q4 = mysqli_query($con,$queryq) or die (mysql_error());
        }
    
    Reply
    • Matt Doyle says

      17 September 2019 at 8:43 am

      What’s the error message?

      Also, never ever insert values from $_POST straight into an SQL string – it’s a massive security hole. Use a prepared statement with placeholders instead.

      Reply
  7. Kevin says

    1 April 2020 at 1:13 am

    Hey Matt ~

    Just a thank you for this post. I get a lot of help and guidance from the enormous numbers of posts on StackOverflow, but every now and again I come across a really nicely explained tutorial or guide like this one. I’m building my first true application in PHP (in conjunction with delivering it through WordPress) and having to relearn a lot of stuff.

    At any rate, much appreciated. Hope you’re fairing well under the novel circumstances.

    ~K

    Reply
    • Matt Doyle says

      14 April 2020 at 2:55 am

      You’re welcome, Kevin! I’m glad my tutorial helped. 🙂 All good here – hope you are doing well also.

      Reply
  8. Simon says

    7 June 2021 at 9:00 pm

    Hi Matt,
    Thanks for the write-up. I do get the feel for the array stuff, but in my case I do not know the size (x and y) of the array I need. I have some 20 or 30 lamps that may be switched on or off. As it happens I get a timestamp, the lamp involved and the new state (on or off). So it seems logical to have an object “switchstamp” that I can array_push onto the array of the lamp switching. That way I get arrays of timestamps per lamp. And as many as I have lamps arrays of that. This is going to be used for making a graph showing when what lamp is switched on a 24hr timescale. So arrays of arrays, but I don’t know how many lamps and how often are switched.
    How to declare such an array?

    Reply
  9. Mohammad Arif Rahim says

    3 July 2021 at 12:56 am

    Hi,
    Can you also describe, how to collected and insert into an previously created array in a function from OOP perspective.

    Reply
  10. SADIK KABIR AHMAD says

    27 August 2021 at 2:11 pm

    idon’t why it show me error please can you help me
    $data = Array(
    do{
    $loadresult[‘subject_code’]=>[‘color’=>[255, 0, 100],’value’=> $loadresult [‘test’]]
    }while($loadresult = $loadquery->fetch(PDO::FETCH_ASSOC));
    );

    Reply
  11. Andrew Koll. says

    16 April 2022 at 7:27 pm

    Dear Matt,
    Your teaching is amazingly short, clear and awesome. I understand lots of things for the first time in my php life. You clearly points to the possible failures. Thank you so much! I will be much more brave with arrays from now. Thank you!

    Reply
    • Matt Doyle says

      21 April 2022 at 8:18 am

      You’re welcome, Andrew. Thanks for your comment 🙂

      Reply

Leave a Reply Cancel reply

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

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits