Cover Image for PHP Indexed Array
187 views

PHP Indexed Array

In PHP, an indexed array is a collection of elements, where each element is associated with a numeric index. The index starts from 0 for the first element, and subsequent elements have increasing index values. Indexed arrays are also commonly known as numeric arrays.

Here’s how you can create and work with indexed arrays in PHP:

  1. Creating an Indexed Array:
    You can create an indexed array using square brackets [ ] and assigning values to specific index positions.

Example:

// Creating an indexed array
$fruits = array("Apple", "Banana", "Orange", "Mango");

or

// Shorter syntax (since PHP 5.4)
$fruits = ["Apple", "Banana", "Orange", "Mango"];
  1. Accessing Elements of an Indexed Array:
    You can access elements of an indexed array using their numeric index.

Example:

echo $fruits[0]; // Output: Apple
echo $fruits[2]; // Output: Orange
  1. Modifying Elements of an Indexed Array:
    You can modify elements of an indexed array by assigning new values to their corresponding index positions.

Example:

$fruits[1] = "Grapes";
echo $fruits[1]; // Output: Grapes
  1. Adding Elements to an Indexed Array:
    You can add elements to the end of an indexed array by using the empty square bracket notation [].

Example:

$fruits[] = "Pineapple";
  1. Looping through an Indexed Array:
    You can use loops like for, foreach, or while to iterate through the elements of an indexed array.

Example (using foreach loop):

foreach ($fruits as $fruit) {
    echo $fruit . " ";
}
// Output: Apple Banana Orange Mango Pineapple
  1. Counting the Number of Elements in an Indexed Array:
    You can use the count() function to get the number of elements in an indexed array.

Example:

$numberOfFruits = count($fruits);
echo $numberOfFruits; // Output: 5

Indexed arrays are useful for storing and working with lists of values, where each value is associated with a numerical position. They provide a simple way to organize and manage data in PHP applications.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS