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 one of the most common and powerful variable types in PHP, allowing you to group related information together efficiently.
Creating a Simple Array
In your code editor, open array.php from the phpclass folder.
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.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.
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.
Return to your code editor to continue building on this foundation.
Comment out the echo statement for clarity:
// echo "My first name is: ".$customer['firstName'];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.
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.
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
Switch back to your code editor to prepare for the next section.
Comment out the echo line to keep your workspace organized:
// echo "My other car is a $cars[0]";
Creating Your First Associative Array
Define Array Elements
Create variables using $customer['key'] syntax with string keys like 'firstName', 'lastName', 'city', and 'state'.
Output Array Values
Use echo with concatenation (period operator) to combine strings with array values for proper display.
Test in Browser
Navigate to localhost to verify your array outputs correctly in the web browser.
Associative vs Indexed Arrays
| Feature | Associative Arrays | Indexed Arrays |
|---|---|---|
| Key Type | String keys ('firstName') | Numeric keys (0, 1, 2) |
| Access Method | $customer['firstName'] | $cars[0] |
| Best Use Case | Structured data | Sequential lists |
| Echo Syntax | Requires concatenation | Can embed directly |
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.
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
Launch MAMP PRO.
In the main window, go to the PHP tab.
Next to Default version make sure the dropdown menu is set to 5.4 or later.
If you've made any changes, click Save.
Return to your code editor.
Checking PHP Version on PC
Launch the XAMPP Control Panel.
To the right of the Apache module, click the Admin button to open a webpage.
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.
If you don't have 5.4 or later, you can go to apachefriends.org to download a newer version of XAMPP.
Return to your code editor.
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.
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.
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
| Feature | Old Syntax (Pre-5.4) | New Syntax (5.4+) |
|---|---|---|
| Declaration | array() | [ ] |
| Key-Value Pairs | array('key' => 'value') | ['key' => 'value'] |
| Readability | More verbose | Cleaner, simpler |
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.
Return to your code editor to build a more complex data structure.
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.
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.
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.
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.
Test your multidimensional array:
- Mac: localhost:8888/phpclass/array.php
- Windows: localhost/phpclass/array.php
You should see: Nobu is very Expensive
Return to your editor to enhance the output with both restaurant entries.
Add a line break for better formatting:
echo $restaurant[0]['name']. ' is very '.$restaurant[0]['price']; echo '<br>';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'];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'];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
Create Empty Container
Start with an empty array using $restaurant = [ ]; to prepare for nested structures.
Add First Nested Array
Insert a complete associative array as the first element with restaurant details like name, type, and price.
Add Additional Elements
Separate multiple nested arrays with commas to create a collection of related data structures.
Access Nested Data
Use double bracket notation like $restaurant[0]['name'] to access specific values in nested arrays.
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.
Return to your code editor to implement array debugging.
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.
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 ) )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.
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
Array Best Practices Checklist
Makes code self-documenting and easier to maintain
Prevents off-by-one errors when accessing elements
Ensures arrays display correctly when combined with strings
Required syntax for valid PHP array structure
Quickly visualize entire array contents and structure