PHP: How to Access Array Elements

To access elements in an array, you can use the keys of the array to retrieve the corresponding values. For example, if there is an array named $arr, you can read the value of the element with the key ‘key’ by using $arr[‘key’]. Here is an example code:

$arr = array('name' => 'John', 'age' => 30);

echo $arr['name']; // 输出 'John'
echo $arr['age']; // 输出 30

In addition to accessing array elements using key-value pairs, you can also use loops to iterate through all the elements in an array. For instance, you can use a foreach loop to iterate through all elements in an associative array.

$arr = array('name' => 'John', 'age' => 30);

foreach ($arr as $key => $value) {
    echo $key . ': ' . $value . '<br>';
}

The above code will generate the output:

name: John
age: 30
bannerAds