Intro to Associative Arrays
Part of the Fundamentals section of Coddy's PHP journey — lesson 41 of 71.
In indexed arrays, you access elements using numeric positions: 0, 1, 2, and so on. But what if you want to access data using meaningful names instead? That's where associative arrays come in.
Associative arrays use keys (usually strings) instead of numeric indexes. Each key is paired with a value, creating a key-value relationship that makes your data more descriptive and easier to work with.
<?php
$person = [
"name" => "Alice",
"age" => 25,
"city" => "Paris"
];
?>The => symbol connects each key to its value. Here, "name" is a key that points to the value "Alice". Instead of remembering that the name is at index 0, you can use the key "name" directly—much more intuitive!
This structure is perfect for representing real-world entities like users, products, or settings, where each piece of data has a clear label. In the upcoming lessons, you'll learn how to access, modify, and add to these key-value pairs.
Cheat sheet
Associative arrays use keys (usually strings) instead of numeric indexes to access elements:
<?php
$person = [
"name" => "Alice",
"age" => 25,
"city" => "Paris"
];
?>The => symbol connects each key to its value, creating key-value pairs.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic7Arrays Part 2 - Associative
Intro to Associative ArraysAccessing Values by KeyModifying Values by KeyAdding New Key-Value PairsCheck if Key ExistsRecap - Key-Value Data Store2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators