PHP Tutorial menu

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
<?php
$cities = ["Karachi", "Lahore", "Islamabad"];

echo $cities[0] . "<br>";
echo $cities[2] . "<br>";
echo "Number of cities: " . count($cities);
Output
Karachi
Islamabad
Number of cities: 3

Add an item to the end with []:

Example

php
<?php
$cities = ["Karachi", "Lahore"];
$cities[] = "Quetta";
print_r($cities);
Output
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
<?php
$student = [
    "name" => "Ayesha",
    "course" => "UI/UX",
    "fee_paid" => true,
];

echo $student["name"] . " studies " . $student["course"] . ".";
Output
Ayesha studies UI/UX.

Multidimensional Arrays

An array can contain other arrays. This is how data from a database usually looks:

Example

php
<?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>";
}
Output
Mouse: Rs 900
Keyboard: Rs 1800
USB Cable: Rs 350

Common Array Functions

FunctionWhat 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
<?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";
Output
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
<?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);
Output
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]?

Learn PHP with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp