Arrays in PHP
Arrays in PHP
Arrays in PHP are used to store multiple values in a single variable. Instead of creating separate variables for each value, arrays allow you to manage collections of data efficiently.
What is an Array in PHP
An array is a data structure that can hold multiple values under one variable name. Each value in an array is assigned an index or key.
Types of Arrays in PHP
Indexed Arrays
Indexed arrays use numeric indexes starting from 0.
$colors = array(“red”, “green”, “blue”);
echo $colors[0]; // red
?>
Associative Arrays
Associative arrays use named keys instead of numeric indexes.
$student = array(
“name” => “John”,
“age” => 20
);
echo $student[“name”];
?>
Multidimensional Arrays
These arrays contain one or more arrays inside them.
$students = array(
array(“John”, 20),
array(“Alice”, 22)
);
echo $students[0][0]; // John
?>
Creating Arrays in PHP
You can create arrays using the array() function or short syntax [].
$numbers = [1, 2, 3, 4];
?>
Accessing Array Elements
You can access elements using their index or key.
echo $numbers[1]; // 2
?>
Looping Through Arrays
Arrays are often used with loops like foreach.
$colors = [“red”, “green”, “blue”];
foreach ($colors as $color) {
echo $color;
}
?>
Common Array Functions
PHP provides built-in functions to work with arrays.
count()– counts elementsarray_push()– adds elementsarray_pop()– removes last element
Why Arrays are Important
Arrays are essential for handling multiple data values efficiently. They are widely used in real-world applications such as storing user data, database results, and form inputs.
Start Your Learning Journey
Want to explore more courses like this? click here for free courses
FAQs – Arrays in PHP
What is an array in PHP
An array is a variable that can store multiple values.
What are types of arrays in PHP
Indexed, associative, and multidimensional arrays.
How do you access array elements
Using index or key values.
What is foreach loop in arrays
It is used to iterate through array elements.
Why use arrays in PHP
They help manage and organize multiple values efficiently.



