Arrays: Free PHP & MySQL Tutorial

Dive into the intricacies of PHP & MySQL with this comprehensive tutorial covering topics like creating a simple array, creating associative arrays using shorthand, and multidimensional arrays.

This exercise is excerpted from Noble Desktop’s past app development training materials and is compatible with iOS updates through 2021. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this PHP & MySQL tutorial:

Creating a simple array, Creating associative arrays using shorthand, Multidimensional arrays, Printing an entire array using print_r()

SQL Bootcamp: Live & Hands-on, In NYC or Online, Learn From Experts, Free Retake, Small Class Sizes,  1-on-1 Bonus Training. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Exercise Overview

One of the most common and powerful types of variables is called an array. Simply put, an array holds lots of information that is grouped together. There are many ways you can create, output, and manipulate arrays, but here we’ll just focus on some of the most commonly-used basics.

Creating a Simple Array

  1. In your code editor, open array.php from the phpclass folder.

  2. In between the <body> tags add the following bold code:

    <?php
    
       $customer['firstName'] = 'Jeremy';
       $customer['lastName'] = 'Kay';
       $customer['city'] = 'New York';
       $customer['state'] = 'NY';
    
    ?>
    

    You’ve just created an array, $customer. The array contains various information about an imaginary customer. This type of array is called an associative array.

  3. Outputting any value from this array is simple. Below the array you just made, add the following bold code:

    $customer['firstName'] = 'Jeremy';
    $customer['lastName'] = 'Kay';
    $customer['city'] = 'New York';
    $customer['state'] = 'NY';
    
    echo "My first name is: " .$customer['firstName'];
    

    This is pretty straightforward, but notice that you have to add a period before the array variable in order to concatenate it to the string. If you don’t, you’ll get an error.

  4. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/array.php
    • Windows: localhost/phpclass/array.php

    Wow. It’s a first name!

  5. Switch back to your code editor.

  6. Comment out the echo line as shown in bold:

    // echo "My first name is: " .$customer['firstName'];
    
  7. Another type of array is called an indexed array. Instead of using words to categorize it we use numbers. Below the echo line, add the following bold code:

    $cars[0] = 'Ferrari';
    $cars[1] = 'Porsche';
    $cars[2] = 'Mustang';
    

    This is an array of our fabulous car collection. One thing to notice is that the first item starts with zero. PHP starts all of its elements as 0, so that is something to keep in mind ($cars[1] is actually the second item in the array).

  8. Echoing an element from this array is a bit easier. Add the following bold code:

    $cars[0] = 'Ferrari';
    $cars[1] = 'Porsche';
    $cars[2] = 'Mustang';
    
    echo "My other car is a $cars[0]";
    
  9. Save the page and then in a browser go to (or reload the page if it’s already open):

    • Mac: localhost:8888/phpclass/array.php
    • Windows: localhost/phpclass/array.php

    The page will read: My other car is a Ferrari

  10. Switch back to your code editor.

  11. Comment out the echo line as shown in bold:

    // echo "My other car is a $cars[0]";
    

Creating Associative Arrays Using Shorthand

In PHP 5.4 and later, a simplified syntax for arrays has been introduced. In previous versions, the array() function was used as a common shorthand for building associative arrays. The current shorthand is even simpler, using just square brackets ([ ])! If you’re not sure which version of PHP you’re using, do the appropriate sidebar as follows.

Checking PHP Version on MAC

  1. Launch MAMP PRO.

  2. In the main window, go to the PHP tab.

  3. Next to Default version make sure the dropdown menu is set to 5.4 or later.

  4. If you’ve made any changes, click Save.

  5. Return to your code editor.

Checking PHP Version on PC

  1. Launch the XAMPP Control Panel.

  2. To the right of the Apache module, click the Admin button to open a webpage.

  3. At the top of the orange sidebar on the left, it says XAMPP followed by a version number, such as [PHP: 5.6.3]. Make sure it says 5.4 or later.

  4. If you don’t have 5.4 or later, you can go to apachefriends.org to download a newer version of XAMPP.

  5. Return to your code editor.

  1. Below the bottom echo line, add the following bold code:

    $restaurant = [
       'name' => 'Nobu',
       'type' => 'Sushi',
       'price' => 'Expensive'
    ];
    

    Here we have created a new array called $restaurant and given it some values. Notice everything goes in between the brackets. The item on the left is called a key, and the element on the right of the => is its value.

  2. Let’s test outputting part of this array. Add the following bold code:

    $restaurant = [
       'name' => 'Nobu',
       'type' => 'Sushi',
       'price' => 'Expensive'
    ];
    
    echo $restaurant['name']. ' is very ' .$restaurant['price'];
    

    Here we simply output the variables and again use the period to concatenate them to our string.

  3. Save the page and then in a browser go to (or reload):

    • Mac: localhost:8888/phpclass/array.php
    • Windows: localhost/phpclass/array.php

    The page will read: Nobu is very Expensive

Multidimensional Arrays

What if you wanted to store a list of many restaurants in one array? We could use what is called a multidimensional array.

  1. Switch back to your code editor.

  2. Delete all the code that has your restaurant info in it (not the echo statement). It’s probably a bit easier just to retype this from scratch. Add the following bold code:

    $restaurant = [
    
    ];
    

    Here we have an empty array awaiting our glory.

  3. In between the empty brackets add the following bold code:

    $restaurant = [
       [
          'name' => 'Nobu',
          'type' => 'Sushi',
          'price' => 'Expensive'
       ]
    ];
    

    Notice we have nested one array inside of another.

  4. Next, add a second element to the main $restaurant array. Add the following bold code:

    $restaurant = [
       [
          'name' => 'Nobu',
          'type' => 'Sushi',
          'price' => 'Expensive'
       ],
       [
          'name' => 'Burger King',
          'type' => 'Fast food',
          'price' => 'Cheap'
       ]
    ];
    

    Be sure to add a comma after the first array! Now we have a second array added to the main $restaurant array.

  5. How would we output this? Let’s check it out. Below the array code modify the echo statement as shown in bold:

    echo $restaurant[0]['name']. ' is very ' .$restaurant[0]['price'];
    

    The [0] in each array element tells PHP to access the first element in the array, which in this case is Nobu.

  6. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/array.php
    • Windows: localhost/phpclass/array.php

    The page will read: Nobu is very Expensive

  7. Switch back to your code editor.

    Let’s add a line break, then output the second element in the array.

  8. Add the following bold code:

    echo $restaurant[0]['name']. ' is very ' .$restaurant[0]['price'];
    echo '<br>';
    
  9. Copy the first echo command, and then paste it below the <br> tag as shown in bold:

    echo $restaurant[0]['name']. ' is very ' .$restaurant[0]['price'];
    echo '<br>';
    echo $restaurant[0]['name']. ' is very ' .$restaurant[0]['price'];
    
  10. Change two instances of 0 to 1 as shown in bold:

    echo $restaurant[0]['name']. ' is very ' .$restaurant[0]['price'];
    echo '<br>';
    echo $restaurant[1]['name']. ' is very ' .$restaurant[1]['price'];
    
  11. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/array.php
    • Windows: localhost/phpclass/array.php

    The page will read:

    Nobu is very Expensive
    Burger King is very Cheap

Printing an Entire Array Using print_r()

During the development of a site, it is often very useful to quickly print out the entire contents of an array.

  1. Switch back to your code editor.

  2. After the last echo statement, add the following bold code:

    print_r($restaurant);
    
  3. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/array.php
    • Windows: localhost/phpclass/array.php

    The page will output the entire array (along with the previous statements):

    Array ( [0] => Array ( [name] => Nobu [type] => Sushi [price] => Expensive ) [1] => Array ( [name] => Burger King [type] => Fast food [price] => Cheap ) )
    
  4. If this code is a bit hard to read, you can view the source in your browser and the formatting will be a lot better:

    Array
    (
       [0] => Array
          (
             [name] => Nobu
             [type] => Sushi
             [price] => Expensive
          )
    
       [1] => Array
          (
             [name] => Burger King
             [type] => Fast food
             [price] => Cheap
          )
    
    )
    

    The source looks better because PHP adds spacing and line breaks, but remember that a browser will ignore whitespace.

  5. Switch back to your code editor and close the file. We’re done with it.

How to Learn Full-Stack Web Development

Master full-stack web development with hands-on training. Build fully functional websites and applications using HTML, CSS, JavaScript, Python, and web developer tools.

Yelp Facebook LinkedIn YouTube Twitter Instagram