Accessing an Array Element in PHP
Accessing array elements is done similarly to accessing string characters. Let's look at an example:
<?php
$arr = ['a', 'b', 'c', 'd', 'e'];
echo $arr[0]; // outputs 'a'
echo $arr[1]; // outputs 'b'
echo $arr[2]; // outputs 'c'
?>
Given an array:
<?php
$arr = ['a', 'b', 'c'];
?>
Output each element of this array to the screen.
Given an array:
<?php
$arr = ['a', 'b', 'c', 'd', 'e'];
?>
Using this array, output the following string:
'a+b+c+d'
Given an array:
<?php
$arr = [1, 2, 3, 4, 5];
?>
Output the sum of the array elements to the screen.
Given an array:
<?php
$arr = [2, 5, 3, 9];
?>
Multiply the first element of the array by the second,
and the third element by the fourth.
Add the results, assign them to the variable
$res
. Output the value
of this variable to the screen.