About Lesson
What is an array?
An array is a special variable that can hold more than one value at a time.
Example:
PHP
<?php
$colors = array("Red", "Green", "Blue");
echo $colors[0]; // Outputs: Red
?>
Types of arrays in PHP
- Indexed Array (numeric keys)
- Associative Array (named keys)
- Multidimensional Array (arrays inside arrays)
1. ✅ Indexed Arrays
Definition: Array with numeric indexes.
Example:
PHP
<?php
$fruits = array("Apple", "Banana", "Orange");
echo $fruits[1]; // Outputs: Banana
?>
Loop through indexed array:
PHP
<?php
for($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i] . "<br>";
}
?>
2. ✅ Associative Arrays
Definition: Array with named (string) keys.
Example:
PHP
<?php
$age = array("John" => 25, "Alice" => 30);
echo $age["Alice"]; // Outputs: 30
?>
Loop through associative array:
PHP
<?php
foreach ($age as $name => $value) {
echo "$name is $value years old.<br>";
}
?>
3. ✅ Multidimensional Arrays
Definition: Arrays containing other arrays.
Example:
PHP
<?php
$contacts = array(
array("Name" => "John", "Phone" => "12345"),
array("Name" => "Alice", "Phone" => "67890")
);
echo $contacts[0]["Name"]; // Outputs: John
?>
Useful array functions
Function | Description |
---|---|
count() | Count elements in an array |
array_push() | Add element at end |
array_pop() | Remove last element |
array_shift() | Remove first element |
array_unshift() | Add element at beginning |
in_array() | Check if a value exists |
sort() | Sort indexed array |
asort() | Sort associative array by value |
ksort() | Sort associative array by key |
Example:
PHP
<?php
$numbers = array(3, 2, 5, 1);
sort($numbers);
print_r($numbers);
?>