In this PHP tutorial, you shall learn how to access elements of an array using index, with example programs.

PHP – Access array elements using index

To access elements of array in PHP, you can use array variables followed by index which is enclosed in square brackets.

The syntax to access element at a specific index in a given array is

</>
Copy
$element = $array[$index]

The index starts from 0 and increments by 1 from left to right of the array. So, the index of first element is 0, the index of second element is 1, the index of third element is 2, and so on.

Examples

1. Access elements in string array using index

In this example, we will take an array of strings, and access second and fourth elements using indexes 1 and 3 respectively.

PHP Program

</>
Copy
<?php
$array = ["apple", "banana", "orange", "mango", "guava"];
$second_element = $array[1];
$fourth_element = $array[3];
echo $second_element;
echo "<br>";
echo $fourth_element;
?>

Output

PHP - Access Array Elements using Index

Conclusion

In this PHP Tutorial, we learned how to access elements of a PHP array using index.