Skip to main content
March 23, 2026Noble Desktop Publishing Team/8 min read

Arrays: Free PHP & MySQL Tutorial

Master PHP Arrays with Hands-On Coding Examples

Array Types You'll Master

Simple Arrays

Basic indexed arrays using numerical positions. Start with zero-based indexing for organizing sequential data like lists.

Associative Arrays

Key-value pair arrays using meaningful string identifiers. Perfect for structured data like customer information.

Multidimensional Arrays

Nested arrays containing other arrays. Essential for complex data structures like database records or product catalogs.

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()

Exercise Overview

Arrays represent one of the most fundamental and powerful data structures in PHP development. At its core, an array is a sophisticated variable that stores multiple related pieces of information in an organized, accessible format. Modern PHP applications rely heavily on arrays for everything from user data management to API responses and database operations. This tutorial focuses on the essential array techniques that every PHP developer needs to master, providing you with practical skills you'll use daily in professional web development.

Arrays Are Fundamental

Arrays are one of the most common and powerful variable types in PHP, allowing you to group related information together efficiently.

Creating a Simple Array

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

  2. Between the <body> tags, add the following code:

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

    You've just created an associative array called $customer. This array structure uses meaningful string keys (like 'firstName') rather than numeric indices, making your code more readable and maintainable. Associative arrays are particularly valuable when working with structured data like user profiles, product information, or configuration settings.

  3. Accessing array values is straightforward and intuitive. Below the array you just created, add the following code:

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

    Notice the concatenation operator (period) that joins the string with the array value. This dot notation is PHP's way of combining different data types into a single output. Without proper concatenation, PHP will throw a parse error.

  4. Save the file and navigate to the following URL in your browser:

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

    You should see the output displaying the first name value from your array.

  5. Return to your code editor to continue building on this foundation.

  6. Comment out the echo statement for clarity:

    // echo "My first name is: ".$customer['firstName'];
  7. Now let's explore indexed arrays, which use numeric keys instead of descriptive strings. Add the following code below the commented echo line:

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

    Indexed arrays are perfect for ordered lists where the position matters more than descriptive keys. A crucial concept to remember: PHP arrays are zero-indexed, meaning the first element is always at position 0, not 1. This is consistent with most programming languages and is essential for avoiding off-by-one errors in your code.

  8. Outputting from indexed arrays offers more flexibility with string interpolation. Add this code:

    $cars[0] = 'Ferrari';
    $cars[1] = 'Porsche';
    $cars[2] = 'Mustang';
    
    echo "My other car is a $cars[0]";

    When embedding array variables directly in double-quoted strings, you can omit the concatenation operator, making your code cleaner and more readable.

  9. Save and refresh your browser page:

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

    The output should read: My other car is a Ferrari

  10. Switch back to your code editor to prepare for the next section.

  11. Comment out the echo line to keep your workspace organized:

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

Creating Your First Associative Array

1

Define Array Elements

Create variables using $customer['key'] syntax with string keys like 'firstName', 'lastName', 'city', and 'state'.

2

Output Array Values

Use echo with concatenation (period operator) to combine strings with array values for proper display.

3

Test in Browser

Navigate to localhost to verify your array outputs correctly in the web browser.

Associative vs Indexed Arrays

FeatureAssociative ArraysIndexed Arrays
Key TypeString keys ('firstName')Numeric keys (0, 1, 2)
Access Method$customer['firstName']$cars[0]
Best Use CaseStructured dataSequential lists
Echo SyntaxRequires concatenationCan embed directly
Recommended: Use associative arrays for structured data with meaningful labels, indexed arrays for simple lists.

Creating Associative Arrays Using Shorthand

Modern PHP development has embraced cleaner, more concise syntax. Since PHP 5.4 (released in 2012), developers have access to simplified array notation using square brackets. This replaced the older array() function syntax, making code more readable and consistent with other modern programming languages. Given that we're now in 2026, this syntax is universally supported and considered the standard approach.

PHP Version Requirements

The simplified square bracket syntax for arrays was introduced in PHP 5.4. Earlier versions required the array() function instead.

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 your commented echo line, implement the modern array syntax:

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

    This concise syntax creates an associative array with key-value pairs. The element before the => operator is the key, while the element after is its corresponding value. This structure mirrors real-world data relationships and is the foundation for working with JSON, APIs, and database results.

  2. Demonstrate array value access and concatenation:

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

    This example shows how to combine multiple array values with string literals using concatenation, a technique you'll frequently use when building dynamic content or user interfaces.

  3. Save and test your code:

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

    Expected output: Nobu is very Expensive

Shorthand Array Syntax Evolution

FeatureOld Syntax (Pre-5.4)New Syntax (5.4+)
Declarationarray()[ ]
Key-Value Pairsarray('key' => 'value')['key' => 'value']
ReadabilityMore verboseCleaner, simpler
Recommended: Use the modern square bracket syntax for cleaner, more readable code in PHP 5.4+.

Multidimensional Arrays

Real-world applications often require storing complex, hierarchical data structures. Multidimensional arrays solve this challenge by allowing you to nest arrays within arrays, creating sophisticated data models that can represent everything from product catalogs to user hierarchies. This approach is particularly valuable when working with APIs, database results, or configuration files.

  1. Return to your code editor to build a more complex data structure.

  2. Replace your existing restaurant code with this foundation:

    $restaurant = [
    
    ];

    Starting with an empty array structure allows you to build complexity incrementally and understand each layer.

  3. Add your first nested array element:

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

    This creates a multidimensional structure where the main array contains other arrays as elements. This pattern is essential for managing collections of related objects.

  4. Expand the array with a second restaurant entry:

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

    The comma separator is crucial for proper array syntax. This structure now represents a collection of restaurants, each with identical properties but different values—a common pattern in application development.

  5. Access multidimensional array data using bracket notation:

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

    The [0] index accesses the first restaurant in the collection. This two-level addressing system (first the collection index, then the property key) is fundamental to working with complex data structures.

  6. Test your multidimensional array:

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

    You should see: Nobu is very Expensive

  7. Return to your editor to enhance the output with both restaurant entries.

  8. Add a line break for better formatting:

    echo $restaurant[0]['name']. ' is very '.$restaurant[0]['price'];
    echo '<br>';
  9. Duplicate and modify the echo statement to display the second restaurant:

    echo $restaurant[0]['name']. ' is very '.$restaurant[0]['price'];
    echo '<br>';
    echo $restaurant[0]['name']. ' is very '.$restaurant[0]['price'];
  10. Update the indices to access the second restaurant:

    echo $restaurant[0]['name']. ' is very '.$restaurant[0]['price'];
    echo '<br>';
    echo $restaurant[1]['name']. ' is very '.$restaurant[1]['price'];
  11. Save and refresh your browser to see both restaurants displayed:

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

    Expected output: Nobu is very Expensive Burger King is very Cheap

Building Multidimensional Arrays

1

Create Empty Container

Start with an empty array using $restaurant = [ ]; to prepare for nested structures.

2

Add First Nested Array

Insert a complete associative array as the first element with restaurant details like name, type, and price.

3

Add Additional Elements

Separate multiple nested arrays with commas to create a collection of related data structures.

4

Access Nested Data

Use double bracket notation like $restaurant[0]['name'] to access specific values in nested arrays.

Zero-Based Indexing

Remember that PHP arrays start at index 0. The first element is [0], the second is [1], and so on.

Printing an Entire Array Using Print_r()

Professional PHP development requires effective debugging techniques. The print_r() function is an indispensable tool for examining array contents during development, troubleshooting data structures, and understanding how your arrays are organized. This function becomes particularly valuable when working with complex multidimensional arrays or debugging API responses.

  1. Return to your code editor to implement array debugging.

  2. Add the print_r() function after your echo statements:

    print_r($restaurant);

    This single line will output the complete array structure, showing all keys, values, and nested relationships.

  3. Save and refresh your browser:

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

    The page will display the complete array structure:

    Array ( [0] => Array ( [name] => Nobu [type] => Sushi [price] => Expensive ) [1] => Array ( [name] => Burger King [type] => Fast food [price] => Cheap ) )
  4. For better readability during development, view your page source (right-click and select "View Source"). The formatted output reveals the true structure:

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

    This formatted view shows the hierarchical structure clearly. PHP includes whitespace and line breaks in the source, but browsers collapse this formatting in the rendered view. Understanding this distinction helps you choose the right debugging approach for different situations.

  5. Return to your code editor and save your work. You've successfully mastered the fundamental array techniques that form the backbone of PHP development.

Using print_r() for Debugging

Pros
Displays complete array structure instantly
Shows all nested elements and their relationships
Essential tool for debugging complex data structures
No need to write individual echo statements
Cons
Output formatting requires viewing page source for readability
Not suitable for production websites
Displays raw array structure rather than formatted content

Array Best Practices Checklist

0/5

Key Takeaways

1Arrays are powerful PHP variables that group related information together using either numeric indices or string keys for organization.
2Associative arrays use meaningful string keys like 'firstName' while indexed arrays use numeric positions starting from zero.
3PHP 5.4+ introduced simplified square bracket syntax [key => value] replacing the older array() function for cleaner code.
4Concatenation with the period operator is required when combining array values with strings in echo statements.
5Multidimensional arrays allow nesting arrays within arrays, accessed using double bracket notation like $array[0]['key'].
6Zero-based indexing means the first array element is at position [0], not [1], which is crucial for proper element access.
7The print_r() function displays entire array structures instantly, making it invaluable for debugging during development.
8Proper comma separation between array elements is essential syntax for valid multidimensional array structures in PHP.

RELATED ARTICLES