0
0
PHPprogramming~5 mins

Indexed array creation in PHP

Choose your learning style9 modes available
Introduction

We use indexed arrays to store lists of items in order. Each item has a number called an index, starting from zero.

When you want to keep a list of names, like a guest list for a party.
When you need to store daily temperatures for a week.
When you want to keep track of scores in a game.
When you want to loop through a list of items one by one.
Syntax
PHP
<?php
// Create an indexed array
$array = array('value1', 'value2', 'value3');

// Or using short syntax
$array = ['value1', 'value2', 'value3'];
?>

Indexed arrays start with index 0 for the first item.

You can use either the array() function or the short [] syntax to create arrays.

Examples
This creates an empty indexed array with no items.
PHP
<?php
// Empty indexed array
$emptyArray = array();
?>
This array has one item at index 0.
PHP
<?php
// Array with one item
$singleItemArray = ["apple"];
?>
This array has three items with indexes 0, 1, and 2.
PHP
<?php
// Array with multiple items
$fruits = ["apple", "banana", "cherry"];
?>
Indexed arrays can hold different types of values together.
PHP
<?php
// Mixing types in an indexed array
$mixedArray = [10, "hello", 3.14];
?>
Sample Program

This program creates an indexed array of colors, prints it, adds a new color, then prints the updated array.

PHP
<?php
// Create an indexed array of colors
$colors = ["red", "green", "blue"];

// Print the array before adding a new color
print_r($colors);

// Add a new color at the end
$colors[] = "yellow";

// Print the array after adding
print_r($colors);
?>
OutputSuccess
Important Notes

Creating an indexed array is very fast, with time complexity O(1) for adding items at the end.

Indexed arrays use memory proportional to the number of items stored.

A common mistake is to confuse indexed arrays with associative arrays, which use named keys instead of numbers.

Use indexed arrays when order matters and you want to access items by their position number.

Summary

Indexed arrays store items in order, starting at index 0.

You can create them using array() or [] syntax.

They are useful for lists where position matters.