What is an Array in PHP?
An array is a special variable that can hold multiple values in a single variable. Instead of creating many variables, an array helps to store and organize data efficiently.
Types of Arrays in PHP
There are three main types of arrays in PHP:
-
Indexed Arrays – Arrays with numeric indexes.
-
Associative Arrays – Arrays with named keys.
-
Multidimensional Arrays – Arrays containing one or more arrays inside them.
1. Indexed Arrays
An indexed array in PHP is an array where elements are stored with numeric indices (starting from 0 by default). It can be created using the array() function or the shorthand [] syntax. Elements in an indexed array can be accessed using their index number.
Indexed arrays can be created in two ways:
- Using
array()function - Using
[](short syntax)
Example 1: Creating an Indexed Array
<?php
// Creating an indexed array using array() function
$fruits = array("Apple", "Banana", "Cherry");
// Creating an indexed array using short syntax
$vegetables = ["Carrot", "Potato", "Spinach"];
// Accessing elements
echo $fruits[0]; // Outputs: Apple
echo $vegetables[2]; // Outputs: Spinach
?>
Example 2: Looping Through an Indexed Array
<?php
$colors = ["Red", "Green", "Blue"];
// Using for loop
for ($i = 0; $i < count($colors); $i++)
{
echo $colors[$i] . "<br>";
}
// Using foreach loop
foreach ($colors as $color)
{
echo $color . "<br>";
}
?>
Example 3: Adding and Removing Elements
<?php
$numbers = [10, 20, 30];
// Adding elements
$numbers[] = 40; // Adds 40 at the end
array_push($numbers, 50, 60); // Adds multiple elements
// Removing the last element
array_pop($numbers);
// Removing a specific element
unset($numbers[1]); // Removes the element at index 1
// Re-indexing the array
$numbers = array_values($numbers);
print_r($numbers);
?>
2. Associative Arrays
An associative array in PHP is an array where keys are strings instead of numeric indices. This allows storing data in key-value pairs for better readability and accessibility.
Example: Various operations on Associative Arrays
<?php
// 1. Creating an Associative Array
$student = [
"name" => "John",
"age" => 25,
"course" => "PHP"
];
// 2. Accessing Elements
echo "Name: " . $student["name"] . "<br>";
echo "Age: " . $student["age"] . "<br>";
// 3. Adding Elements
$student["grade"] = "A";
echo "Added Grade: " . $student["grade"] . "<br>";
// 4. Updating Elements
$student["age"] = 26;
echo "Updated Age: " . $student["age"] . "<br>";
// 5. Removing an Element
unset($student["course"]);
echo "After removing course:<br>";
print_r($student);
echo "<br>";
// 6. Checking if a Key Exists
if (array_key_exists("name", $student)) {
echo "Key 'name' exists in the array.<br>";
}
// 7. Looping Through an Associative Array
echo "Student Details:<br>";
foreach ($student as $key => $value) {
echo "$key: $value <br>";
}
// 8. Getting All Keys and Values
$keys = array_keys($student);
$values = array_values($student);
echo "Keys: ";
print_r($keys);
echo "<br>Values: ";
print_r($values);
echo "<br>";
// 9. Sorting Operations
asort($student); // Sort by values (ascending)
echo "Sorted by Values (Ascending):<br>";
print_r($student);
echo "<br>";
ksort($student); // Sort by keys (ascending)
echo "Sorted by Keys (Ascending):<br>";
print_r($student);
echo "<br>";
// 10. Merging Two Associative Arrays
$extraInfo = ["city" => "New York", "country" => "USA"];
$student = array_merge($student, $extraInfo);
echo "After Merging:<br>";
print_r($student);
echo "<br>";
// 11. Counting Elements
echo "Total Elements in Array: " . count($student) . "<br>";
?>
3. Multidimensional Arrays
A multidimensional array in PHP is an array that contains one or more arrays as elements. It is used to store data in a tabular (row-column) format.
Types of Multidimensional Arrays:
- Two-Dimensional Arrays: A 2-dimensional array in PHP is an array that contains arrays as its elements, allowing you to represent data in a table-like structure (rows and columns).
- Three-Dimensional Arrays: A 3-dimensional array in PHP is an array that contains arrays of arrays, allowing you to represent data in a more complex structure (like a cube of data).
Example 1: Two-Dimensional Array
<?php
$students = [
["John", 25, "PHP"],
["Alice", 23, "Java"],
["Bob", 24, "Python"]
];
// Accessing elements
echo $students[0][0]; // Outputs: John
echo $students[1][2]; // Outputs: Java
?>
Example 2:
<?php
// Creating a multidimensional array
$students = array(
array("John", 20, "PHP"),
array("Sara", 22, "JavaScript"),
array("Mike", 19, "Python")
);
// Accessing elements
echo $students[0][0]; // Outputs: John
// Looping through a multidimensional array
foreach ($students as $student) {
echo "Name: " . $student[0] . " - Age: " . $student[1] . " - Course: " . $student[2] . "<br>";
}
?>