![]() |
VOOZH | about |
In PHP, an indexed array is a type of array where each element is assigned an index number. By default, the index of the first element starts at 0, the second element gets index 1, and so on. This sequential indexing makes it easy to access and manipulate array elements.
Indexed arrays in PHP can be created in two ways:
array() functionYou can access elements in an indexed array by referring to their index number.
Parker
To modify an array element, simply refer to its index and assign a new value.
array(4) {
[0]=>
int(10)
[1]=>
int(20)
[2]=>
int(35)
[3]=>
int(40)
}
PHP provides multiple ways to loop through indexed arrays. The most common way is using a foreach loop.
Volvo BMW Toyota
Another way is by using a for loop, especially when you need to access both the index and value.
USA Canada Mexico Brazil
You can use the array_push() function to add new items to an indexed array. PHP will automatically assign the next available index.
array(4) {
[0]=>
string(3) "red"
[1]=>
string(5) "green"
[2]=>
string(4) "blue"
[3]=>
string(5) "black"
}
You can remove items from an indexed array using the array_pop() function, which removes the last item from the array.
array(3) {
[0]=>
string(6) "carrot"
[1]=>
string(6) "tomato"
[2]=>
string(8) "cucumber"
}
An indexed array can also be traversed in reverse order using a while loop.
5 4 3 2 1
PHP provides several built-in functions to work with indexed arrays. Some of the most common functions include: