PHP - Indexed Array

Welcome to our journey into the world of PHP programming! Today, we'll dive deep into one of the most fundamental concepts in PHP: indexed arrays. These arrays are like a treasure trove of data, waiting to be unearthed and utilized. So, let's get started!

PHP - Indexed Array

What is an Indexed Array?

An indexed array in PHP is a type of array where each element has an associated index or key. Think of it as a list with numbers on it, where each number corresponds to a specific item. For example, you might have a shopping list where each item has a number next to it:

1. Apples
2. Bananas
3. Oranges

In PHP, you can create an indexed array using the array() function or the shorthand [] syntax. Here's how you can create an indexed array for our shopping list:

$shoppingList = array("Apples", "Bananas", "Oranges");
// Or using shorthand syntax
$shoppingList = ["Apples", "Bananas", "Oranges"];

Now that we have our shopping list stored in an indexed array, let's explore how we can access its elements.

Accessing the Array Elements Using Index

To access an element in an indexed array, you use its index. In PHP, array indices start at 0, so the first element is accessed with 0, the second with 1, and so on. Here's how you can access the first item in our shopping list:

echo $shoppingList[0]; // Outputs: Apples

Similarly, you can access the last item by using the negative index:

echo $shoppingList[-1]; // Outputs: Oranges

Traversing an Indexed Array Using "foreach" Loop

One of the most common ways to traverse an indexed array is by using a foreach loop. This loop allows you to go through each element in the array one by one. Here's how you can print out all the items in our shopping list using a foreach loop:

foreach ($shoppingList as $item) {
    echo $item . "\n";
}

When you run this code, it will output:

Apples
Bananas
Oranges

Inside the foreach loop, the variable $item takes on the value of each element in the array $shoppingList. The "\n" is used to add a new line after each item, making the output easier to read.

Conclusion

And there you have it! You've now learned the basics of working with indexed arrays in PHP. Remember, practice makes perfect, so try creating your own indexed arrays and experimenting with different ways to access and traverse them. With time and practice, you'll become a pro at handling these powerful tools in PHP. Happy coding!

Credits: Image by storyset