Arrays are one of the most fundamental and widely-used data structures in PHP. They can hold multiple values in a single variable. In PHP, there are three types of arrays:
Creating an Indexed Array You can create an indexed array using the `array()` function or the shorthand `[]` syntax:
// Using array() function
$numbers = array(1, 2, 3, 4, 5);
// Using [] shorthand
$fruits = ["apple", "banana", "cherry"];
Accessing Values To access the value of an element, use the square bracket notation `[]`:
echo $numbers[0]; // Output: 1
echo $fruits[2]; // Output: cherry
Looping Through an Indexed Array
for ($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i] . "<br>";
}
or
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
Creating an Associative Array
$person = array(
"name" => "John",
"age" => 30,
"country" => "USA"
);
// OR
$person = [
"name" => "John",
"age" => 30,
"country" => "USA"
];
Accessing Values
echo $person["name"]; // Output: John
Looping Through an Associative Array
foreach ($person as $key => $value) {
echo $key . ": " . $value . "<br>";
}
Creating a Multidimensional Array
$students = [
["name" => "John", "grade" => 90],
["name" => "Jane", "grade" => 85],
["name" => "Sam", "grade" => 92]
];
Accessing Values
echo $students[0]["name"]; // Output: John
Looping Through a Multidimensional Array
foreach ($students as $student) {
echo "Name: " . $student["name"] . ", Grade: " . $student["grade"] . "<br>";
}
$arr = [3, 1, 4, 1, 5];
sort($arr); // Output: [1, 1, 3, 4, 5]
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here