Skip to content
PHP Logo

How can dynamic array elements be accessed in PHP?

To access elements in a dynamic array in PHP, you can use square brackets with the index of the element you want to access. The index starts at 0 for the first element, 1 for the second, and so on. This allows you to retrieve or modify specific elements within the array.

php
// Example of accessing elements in a dynamic array
$dynamicArray = [10, 20, 30, 40, 50];

// Accessing the second element (index 1)
echo $dynamicArray[1]; // Output: 20

// Modifying the third element (index 2)
$dynamicArray[2] = 35;

// Adding a new element to the end of the array
$dynamicArray[] = 60;

// Looping through all elements in the array
foreach ($dynamicArray as $element) {
    echo $element . " ";
}