Sling Academy
Home/PHP/Exploring Indexed and Associative Arrays in PHP

Exploring Indexed and Associative Arrays in PHP

Last updated: January 10, 2024

Overview

Arrays in PHP are versatile data structures that allow you to store multiple values in a single variable. Indexed and associative arrays are two fundamental types that differ in how their elements are referenced—using sequential indices or named keys, respectively.

Introduction to Arrays in PHP

In PHP, arrays are extensively used for storing and manipulating data. An indexed array automatically assigns a numeric index starting from 0, while an associative array lets you use strings as keys. Both can store values of any data type, and this guide provides insights with practical examples.

Creating Indexed Arrays

Here’s how you can create an indexed array in PHP:

$fruits = array('apple', 'banana', 'cherry');
// Short array syntax
$vegetables = ['carrot', 'pea', 'broccoli'];

Both lines above establish arrays with numeric indices assigned starting from 0.

Accessing Indexed Array Elements

To access the elements of an indexed array, you use the numeric index like this:

echo $fruits[0]; // Outputs: apple
echo $vegetables[2]; // Outputs: broccoli

Creating Associative Arrays

Associative arrays use named keys that you can define as follows:

$person = array('firstName' => 'John', 'lastName' => 'Doe', 'age' => 30);
// Short array syntax
$color_codes = ['red' => '#FF0000', 'green' => '#00FF00', 'blue' => '#0000FF'];

Accessing Associative Array Elements

Associative array elements are accessed using their named keys:

echo $person['firstName']; // Outputs: John
echo $color_codes['blue']; // Outputs: #0000FF

Looping Through Arrays

Use foreach to iterate over both indexed and associative arrays:

foreach ($fruits as $fruit) {
    echo $fruit . "\n";
}

foreach ($person as $key => $value) {
    echo "$key: $value\n";
}

Adding and Removing Elements

Arrays in PHP are dynamic. Here’s how to add and remove elements:

// Adding to an indexed array
$fruits[] = 'durian';

// Adding to an associative array
$person['email'] = '[email protected]';

// Removing an element by unset()
unset($fruits[1]); // Removes 'banana'

Advanced Array Functions

PHP offers numerous functions to manipulate arrays:

// Searching for an element
$key = array_search('cherry', $fruits);

// Sorting an array
sort($fruits);

// Filtering an array
$adults = array_filter($person, function($age) { return $age >= 18; });

Multidimensional Arrays

Multidimensional arrays are arrays of arrays, which are commonly used for complex data structures:

$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

echo $matrix[0][1]; // Outputs: 2

Tips and Common Mistakes

Be careful with array indices, as undefined index errors are common. Also, remember that array functions that sort or filter are often not suitable for associative arrays as they might re-index the array and can lead to data loss.

Conclusion

In this guide, we’ve explored the foundations of indexed and associative arrays in PHP, complete with code examples for clarity. Remember, mastery of array manipulation can significantly enhance your coding projects and understanding these basics is key to better PHP development.

Next Article: How to Access Array Elements in PHP

Previous Article: 5 Ways to Create an Array in PHP

Series: PHP Data Structure Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array