Topics Arrays & Collections Indexed & Associative Arrays
beginner 12 min read

Indexed & Associative Arrays

Creating, accessing, and manipulating arrays in PHP.

Array Syntax

// Indexed
\$colors = ["red", "green", "blue"];
echo \$colors[0]; // red

// Associative
\$user = [
"name" => "Alice",
"email" => "[email protected]",
];
echo \$user["email"];

// Short syntax (PHP 5.4+)
\$nums = [1, 2, 3];

// Array destructuring (PHP 7.1+)
[\$a, \$b] = [1, 2];
['name' => \$name] = \$user;

Multidimensional Arrays

\$matrix = [[1,2],[3,4]];
echo \$matrix[0][1]; // 2

Examples

<?php
$person = ['name'=>'Bob','age'=>25,'city'=>'NYC'];
echo $person['name'] . ' is ' . $person['age'];
[$a, $b, $c] = [10, 20, 30];
echo $a + $b + $c;

Your Notes

Sign in to take notes for this lesson.

Quiz

Arrays Quiz

0 questions

Sign in to take quiz

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.