PHP Arrays

PHP Arrays

An array stores multiple values in a single variable. PHP arrays are dynamic and can hold mixed types.

1 - Indexed Arrays

$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0]; // Apple
echo count($fruits); // 3

2 - Associative Arrays

$user = [
    "name"  => "Alice",
    "email" => "[email protected]",
    "age"   => 30
];

echo $user["name"]; // Alice

3 - Multidimensional Arrays

$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

echo $matrix[1][2]; // 6

4 - Useful Array Functions

$nums = [3, 1, 4, 1, 5, 9];

array_push($nums, 2);          // add to end
array_pop($nums);              // remove from end
array_shift($nums);            // remove from front
array_unshift($nums, 0);       // add to front
array_unique($nums);           // remove duplicates
in_array(5, $nums);            // true/false check
array_search(5, $nums);        // returns key
array_slice($nums, 1, 3);      // extract portion
array_merge($a, $b);           // merge arrays
array_map(fn($n) => $n * 2, $nums);  // transform
array_filter($nums, fn($n) => $n > 3); // filter

Note: PHP arrays are ordered maps internally. They maintain insertion order and can use any integer or string as keys — making them work as lists, dictionaries, stacks, and queues.

-Tip-