⊗ppPmArVK 65 of 447 menu

Variable Keys in PHP

Suppose we have the following array:

<?php $arr = ['a', 'b', 'c']; ?>

Let's output the element with key 0:

<?php $arr = ['a', 'b', 'c']; echo $arr[0]; // outputs 'a' ?>

Now, let's not write the key of the element to output directly in the square brackets, but store it in a variable:

<?php $arr = ['a', 'b', 'c']; $key = 0; // store the key in a variable ?>

Now let's use our variable to output the corresponding element:

<?php $arr = ['a', 'b', 'c']; $key = 0; // store the key in a variable echo $arr[$key]; // outputs 'a' ?>

Given the following variables:

<?php $arr = [1, 2, 3, 4, 5]; $key1 = 1; $key2 = 2; ?>

Find the sum of the elements whose keys are stored in the variables.

Given the following variables:

<?php $arr = ['a' => 1, 'b' => 2, 'c' => 3]; $key = 'b'; ?>

Output the array element whose key is stored in the variable $key.

byenru