Indexed Arrays
Introduction
In PHP, an array is a type of data structure that allows us to store multiple values in a single variable. Arrays in PHP can be categorized into three types: Indexed arrays, Associative arrays, and Multidimensional arrays. In this tutorial, we'll focus on Indexed arrays, which are the simplest type of arrays.
What is an Indexed Array?
An indexed array is an array where the values are stored in a linear fashion. The index in indexed arrays is an integer that starts at 0 and increases by 1 for each value. For example, if we have an array of five elements, the indices would be 0, 1, 2, 3, and 4.
Creating an Indexed Array
Creating an indexed array in PHP is straightforward. We use the array()
function, and the values are separated by commas. Here's an example:
$fruits = array("Apple", "Banana", "Cherry", "Date", "Elderberry");
In this example, we've created an indexed array called $fruits
with five elements. "Apple" is at index 0, "Banana" at index 1, and so on.
Accessing Array Elements
We can access the individual elements of an array using their indices. Here's how you would access the second element ("Banana") of the $fruits
array:
echo $fruits[1]; // Outputs: Banana
Remember, array indices start at 0, so the index of the second element is 1.
Looping Through an Indexed Array
To access all elements of an array, you can use a for
loop. Here's how:
for($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i];
echo "<br>";
}
The count()
function returns the number of elements in the array. This loop will print each fruit on a new line.
Adding Elements to an Indexed Array
You can add elements to an indexed array using the []
operator. Here's how you add "Fig" to the $fruits
array:
$fruits[] = "Fig";
This will add "Fig" at the end of the array, at the next available index.
Conclusion
Indexed arrays are a fundamental part of PHP, and understanding them is key to becoming proficient in the language. They allow you to store and manipulate multiple values at once, making your code more efficient and organized. Practice creating, accessing, and modifying indexed arrays to get comfortable with them. In the next tutorial, we'll discuss associative arrays, which allow you to use arbitrary keys instead of numerical indices.