Home > Mobile >  Simple Numeric array questions
Simple Numeric array questions

Time:07-21

I am given this array

$names = ['John', 'James', 'Joe'];

And these questions

  • How would you assign the number of names in the array to a variable called $total?
  • How would you use the $total variable to assign the last name to a new variable called $last?

The answer for the first question I figured out is

$total = count($names);

to get the number of names in the names array. But when I go to the second question I am trying to use the $total variable to assign the last name to a new variable called last. I get this

$last = $total[2]

which is incorrect. I get the error

Trying to access array offset on value of type int

Any help would be most appreciated!

CodePudding user response:

Consider utilizing $total when finding the last name instead of hard coding 2:

<?php
$names = ['John', 'James', 'Joe'];
echo "\$names = " . PHP_EOL;
print_r($names);
$total = count($names);
echo "\$total = " . $total . PHP_EOL;
$last = $names[$total - 1];
echo "\$last = " . $last . PHP_EOL;

Output:

$names = 
Array
(
    [0] => John
    [1] => James
    [2] => Joe
)
$total = 3
$last = Joe
  • Related