PHP Indexed Array
An indexed array in PHP is an array that stores values in a numeric index, starting from 0 and incrementing by 1 for each element. It is the most basic type of array in PHP that is widely used in programming. In this tutorial, we will learn how to declare, initialize, and access indexed arrays in PHP.
Syntax
The syntax for creating an indexed array in PHP is as follows:
$my_array = array(value1, value2, value3, ...);
The values can be of any data type, including string, integer, float, and boolean.
Alternatively, we can use the short syntax to declare an indexed array:
$my_array = [value1, value2, value3, ...];
Example
Let's start with a simple example to demonstrate how to create and access an indexed array in PHP:
$fruits = array("apple", "banana", "cherry");
echo $fruits[0]; // outputs "apple"
echo $fruits[1]; // outputs "banana"
echo $fruits[2]; // outputs "cherry"
In this example, we declare an indexed array $fruits
that contains three string values. We then use the index to access and print each element of the array using the echo
statement.
Output
The output of the above example will be:
apple
banana
cherry
Explanation
In the above example, we created an indexed array $fruits
using the array()
construct and initialized it with three string values: "apple", "banana", and "cherry". We then accessed the elements of the array using their indexes and printed them using the echo
statement.
The first element of the array has an index of 0, the second element has an index of 1, and the third element has an index of 2. Keep in mind that the index of an array always starts from 0 and increments by 1 for each element.
Use
Indexed arrays are used in PHP for storing a list of related values under a single variable name. They are commonly used to store data like names, numbers, and other related information. Indexed arrays can be passed as arguments to functions, returned from functions, or used in logical and arithmetic operations.
Important Points
- Indexed arrays are the most basic type of PHP array that stores values in a numeric index starting from 0.
- The
array()
construct is used to create an indexed array in PHP, but the short syntax[]
can also be used. - To access an individual element of an indexed array, we use the index enclosed in square brackets
[]
. - The index of an array always starts from 0 and increments by 1 for each element.
- Indexed arrays can contain values of any data type, including string, integer, float, and boolean.
Summary
In this tutorial, we learned how to declare, initialize, and access indexed arrays in PHP. We also explored the syntax and example of indexed arrays, their use cases, and important points to remember. By mastering the use of indexed arrays, you can efficiently store and manipulate data in your PHP programs.