Skip to content
PHP

Arrays and Array Functions in PHP

Create indexed, associative, and multidimensional arrays with map and filter.

By EZ4Code Team
arraybeginner

Code

<?php

// Indexed array
$fruits = ["apple", "banana", "cherry"];
echo count($fruits);

// Associative array
$user = ["name" => "Alice", "age" => 30];
echo $user["name"];

// Multidimensional
$users = [
    ["name" => "Alice", "age" => 30],
    ["name" => "Bob", "age" => 25],
];

// Array functions
$upper = array_map(fn($n) => strtoupper($n), $fruits);
$adults = array_filter($users, fn($u) => $u["age"] >= 18);
$names = array_column($users, "name");
usort($users, fn($a, $b) => $a["age"] <=> $b["age"]);

// Add / remove
array_push($fruits, "date");
$last = array_pop($fruits);

Explanation

PHP supports indexed, associative, and multidimensional arrays, all using the same array() or [] syntax. array_map and array_filter apply callbacks for transformation and selection, while array_column extracts a single field from nested arrays. usort with the spaceship operator (<=>) provides concise custom sorting.

More PHP Snippets