PHP Arrays
An array stores many values in one variable, such as a list of students or a price list.
Indexed Arrays
Items get numbers (indexes) starting from 0:
Example
<?php
$cities = ["Karachi", "Lahore", "Islamabad"];
echo $cities[0] . "<br>";
echo $cities[2] . "<br>";
echo "Number of cities: " . count($cities);Karachi Islamabad Number of cities: 3
Add an item to the end with []:
Example
<?php
$cities = ["Karachi", "Lahore"];
$cities[] = "Quetta";
print_r($cities);Array ( [0] => Karachi [1] => Lahore [2] => Quetta )
print_r() shows the whole array, which is helpful while testing.
Associative Arrays
Here you choose the keys yourself, usually as text:
Example
<?php
$student = [
"name" => "Ayesha",
"course" => "UI/UX",
"fee_paid" => true,
];
echo $student["name"] . " studies " . $student["course"] . ".";Ayesha studies UI/UX.
Multidimensional Arrays
An array can contain other arrays. This is how data from a database usually looks:
Example
<?php
$products = [
["name" => "Mouse", "price" => 900],
["name" => "Keyboard", "price" => 1800],
["name" => "USB Cable", "price" => 350],
];
foreach ($products as $p) {
echo $p["name"] . ": Rs " . $p["price"] . "<br>";
}Mouse: Rs 900 Keyboard: Rs 1800 USB Cable: Rs 350
Common Array Functions
| Function | What it does |
|---|---|
count($a) | Number of items |
in_array($v, $a) | true if the value exists |
array_key_exists($k, $a) | true if the key exists |
sort($a) / rsort($a) | Sort values up / down |
asort($a) / ksort($a) | Sort by value / by key, keeping keys |
array_push($a, $v) | Add to the end |
array_pop($a) | Remove from the end |
array_merge($a, $b) | Join two arrays |
array_sum($a) | Add all numbers |
implode(", ", $a) | Join items into a string |
explode(",", $s) | Split a string into an array |
Example
<?php
$marks = [65, 92, 78, 50];
sort($marks);
echo implode(", ", $marks) . "<br>";
echo "Highest: " . max($marks) . "<br>";
echo in_array(92, $marks) ? "Someone got 92" : "No 92";50, 65, 78, 92 Highest: 92 Someone got 92
Filtering and Mapping
array_filter() keeps items that pass a test. array_map() changes every item.
Example
<?php
$prices = [200, 1500, 750, 3000];
$expensive = array_filter($prices, fn($p) => $p > 1000);
$withTax = array_map(fn($p) => $p * 1.1, $prices);
echo implode(", ", $expensive) . "<br>";
echo implode(", ", $withTax);1500, 3000 220, 1650, 825, 3300
sort() changes the original array and resets the keys. Use asort() if you want to keep the keys of an associative array.
Exercise
Exercise
In $colors = ["red", "green", "blue"], what is $colors[1]?
