Indexed and Associative Arrays
PHP arrays are flexible — they can be indexed (numbered) or associative (key-value pairs). A single array can mix both.
Example
<?php
// Indexed array
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0]; // "Apple"
$fruits[] = "Date"; // append
// Associative array
$user = [
"name" => "Alice",
"email" => "alice@example.com",
"age" => 25
];
echo $user["name"]; // "Alice"
// Common functions
echo count($fruits); // 4
sort($fruits); // sort ascending
array_push($fruits, "Fig"); // add to end
array_pop($fruits); // remove from end
in_array("Apple", $fruits); // true
array_merge($arr1, $arr2); // combine arrays
array_keys($user); // ["name", "email", "age"]
array_values($user); // ["Alice", "alice@...", 25]
// Array destructuring
[$a, $b, $c] = [1, 2, 3];
["name" => $name] = $user;
?> Array Functions
PHP has powerful array functions for filtering, mapping, and reducing.
Example
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter
$evens = array_filter($numbers, fn($n) => $n % 2 === 0);
// [2, 4, 6, 8, 10]
// Map
$doubled = array_map(fn($n) => $n * 2, $numbers);
// [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
// Reduce
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
// 55
// Slice
$first3 = array_slice($numbers, 0, 3); // [1, 2, 3]
// Unique
$unique = array_unique([1, 2, 2, 3, 3]); // [1, 2, 3]
// Sort associative by value/key
$ages = ["Bob" => 30, "Alice" => 25];
asort($ages); // sort by value
ksort($ages); // sort by key
?> 