PHP Index and associative arrays

PHP Arrays: Indexed vs Associative

PHP has two main types of arrays: indexed arrays and associative arrays. Here's a breakdown of both:

Indexed Arrays

  • Use numeric indexes starting from 0

  • Automatically assigned indexes

  • Created with array() or [] (short array syntax)

php
// Creating an indexed array
$colors = array("Red", "Green", "Blue");
// or
$colors = ["Red", "Green", "Blue"];

// Accessing elements
echo $colors[0]; // Outputs: Red

// Adding elements
$colors[] = "Yellow"; // Adds to the end

Associative Arrays

  • Use named keys (strings) instead of numeric indexes

  • Key-value pairs

  • Useful for representing structured data

php
// Creating an associative array
$person = [
    "name" => "John",
    "age" => 30,
    "city" => "New York"
];

// Accessing elements
echo $person["name"]; // Outputs: John

// Adding elements
$person["email"] = "john@example.com";

Key Differences

FeatureIndexed ArrayAssociative Array
KeysNumeric (0,1,2...)String/named keys
OrderImportantNot guaranteed in PHP
Use caseSimple listsStructured data

Common Operations

php
// Looping through indexed array
foreach ($colors as $color) {
    echo $color . "\n";
}

// Looping through associative array
foreach ($person as $key => $value) {
    echo "$key: $value\n";
}

// Checking if key exists
if (array_key_exists("age", $person)) {
    echo "Age exists!";
}

// Getting all keys
$keys = array_keys($person);

// Getting all values
$values = array_values($person);

PHP arrays are actually ordered maps (can act as both lists and dictionaries), so even indexed arrays are technically associative arrays with integer keys.

To Top