Arrays in PHP let you store multiple values in a single variable. An indexed array uses numeric keys (starting from 0) to store elements. Let’s explore how to create, access, and manipulate indexed arrays! 🚀
🔹 Creating an Indexed Array
Here’s how to create a simple indexed array:
<?php
// Creating an indexed array
$fruits = array("Apple", "Banana", "Cherry");
// Displaying an element
echo $fruits[0]; // Outputs: Apple
?>
Explanation:
$fruits[0]→ First item (“Apple”).$fruits[1]→ Second item (“Banana”).$fruits[2]→ Third item (“Cherry”).
🔹 Adding & Modifying Elements
You can add new items by assigning a value to the next index.
<?php
$colors = array("Red", "Green", "Blue");
// Adding a new element
$colors[] = "Yellow";
// Modifying an element
$colors[1] = "Purple";
print_r($colors);
?>
Output: Array ( [0] => Red, [1] => Purple, [2] => Blue, [3] => Yellow )
🔹 Looping Through an Indexed Array
Use a foreach loop to iterate over the array.
<?php
$animals = array("Dog", "Cat", "Elephant");
foreach ($animals as $animal) {
echo "I love $animal! <br>";
}
?>
Output:
I love Dog!
I love Cat!
I love Elephant!
🔹 Counting Elements in an Array
Use count() to find the number of items in an array.
<?php
$cars = array("BMW", "Toyota", "Honda");
echo "Total cars: " . count($cars);
?>
Output: Total cars: 3
🔹 Sorting an Indexed Array
You can sort arrays alphabetically or numerically using sort().
<?php $numbers = array(42, 15, 8, 99); sort($numbers); print_r($numbers); ?>
Output: Array ( [0] => 8, [1] => 15, [2] => 42, [3] => 99 )
🎯 Key Takeaways
- An indexed array stores multiple values using numeric keys.
- Elements can be added, modified, and removed dynamically.
- Use
foreachto loop through the array. - Use
count()to get the number of elements. - Sort arrays with
sort()for ordered lists.
📝 Practice Time!
Try creating your own array of favorite movies, superheroes, or pizza toppings! 🍕