PHP Indexed Arrays

Welcome to The Coding College! In this tutorial, we’ll explore PHP Indexed Arrays, a crucial feature of PHP that lets you store and manage multiple values in a single variable using numeric indexes. Indexed arrays are simple, efficient, and a fundamental part of working with data in PHP.

What Are PHP Indexed Arrays?

An indexed array is a type of array in PHP where each element is associated with a numeric index. These indexes start from 0 by default, but you can also specify custom numeric indexes.

How to Create an Indexed Array

Method 1: Using the array() Function

<?php
$fruits = array("Apple", "Banana", "Cherry");
?>

Method 2: Using Square Brackets (PHP 5.4+)

<?php
$fruits = ["Apple", "Banana", "Cherry"];
?>

Accessing Elements in an Indexed Array

You can access elements in an array using their index. Remember, the first element has an index of 0.

Example:

<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0]; // Output: Apple
echo $fruits[1]; // Output: Banana
echo $fruits[2]; // Output: Cherry
?>

Adding Elements to an Indexed Array

You can add elements to an array dynamically using the square bracket syntax or array_push().

Example:

<?php
$fruits = ["Apple", "Banana"];
$fruits[] = "Cherry"; // Add element
array_push($fruits, "Orange", "Grapes"); // Add multiple elements
print_r($fruits);
?>

Output:

Array ( [0] => Apple [1] => Banana [2] => Cherry [3] => Orange [4] => Grapes )

Looping Through an Indexed Array

You can iterate through indexed arrays using loops like for or foreach.

Example: Using a for Loop

<?php
$fruits = ["Apple", "Banana", "Cherry"];
for ($i = 0; $i < count($fruits); $i++) {
    echo $fruits[$i] . "<br>";
}
?>

Example: Using a foreach Loop

<?php
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}
?>

Modifying Elements in an Indexed Array

You can modify any element in an array by referencing its index.

Example:

<?php
$fruits = ["Apple", "Banana", "Cherry"];
$fruits[1] = "Blueberry"; // Replace Banana with Blueberry
print_r($fruits);
?>

Output:

Array ( [0] => Apple [1] => Blueberry [2] => Cherry )

Removing Elements from an Indexed Array

To remove elements from an indexed array, you can use the unset() function.

Example:

<?php
$fruits = ["Apple", "Banana", "Cherry"];
unset($fruits[1]); // Remove Banana
print_r($fruits);
?>

Output:

Array ( [0] => Apple [2] => Cherry )

Notice that the index 1 is not re-assigned automatically. To re-index the array, you can use the array_values() function.

Re-indexing Example:

<?php
$fruits = array_values($fruits); // Re-index the array
print_r($fruits);
?>

Output:

Array ( [0] => Apple [1] => Cherry )

Sorting Indexed Arrays

PHP provides functions to sort indexed arrays in ascending or descending order.

Sort in Ascending Order (sort())

<?php
$fruits = ["Cherry", "Apple", "Banana"];
sort($fruits);
print_r($fruits);
?>

Output:

Array ( [0] => Apple [1] => Banana [2] => Cherry )

Sort in Descending Order (rsort())

<?php
$fruits = ["Cherry", "Apple", "Banana"];
rsort($fruits);
print_r($fruits);
?>

Output:

Array ( [0] => Cherry [1] => Banana [2] => Apple )

Useful PHP Functions for Indexed Arrays

FunctionDescriptionExample
count()Returns the number of elements in the arraycount($fruits)
array_push()Adds one or more elements to the endarray_push($fruits, "Orange")
array_pop()Removes the last elementarray_pop($fruits)
in_array()Checks if a value exists in the arrayin_array("Apple", $fruits)
array_search()Searches for a value and returns its indexarray_search("Banana", $fruits)

Example: Combining Functions

<?php
$fruits = ["Apple", "Banana", "Cherry"];

// Add elements
array_push($fruits, "Orange", "Grapes");

// Check if an element exists
if (in_array("Apple", $fruits)) {
    echo "Apple is in the array.<br>";
}

// Search for an element
$key = array_search("Banana", $fruits);
echo "Banana is at index: $key<br>";

// Sort the array
sort($fruits);
print_r($fruits);
?>

Output:

Apple is in the array.  
Banana is at index: 1  
Array ( [0] => Apple [1] => Banana [2] => Cherry [3] => Grapes [4] => Orange )

Best Practices for Working with Indexed Arrays

  1. Use Meaningful Variable Names: Choose descriptive names that reflect the data.
  2. Keep Indexes in Mind: Understand how PHP assigns indexes.
  3. Utilize Built-in Functions: Leverage PHP’s rich array functions to simplify your code.
  4. Avoid Magic Numbers: Use count() for dynamic loops instead of hardcoding array lengths.

Conclusion

Indexed arrays are one of the simplest yet most versatile features in PHP. By mastering indexed arrays, you can manage collections of data efficiently and write cleaner, more maintainable code.

For more tutorials and coding resources, visit The Coding College. Let’s continue learning and coding together!

Leave a Comment