Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Simple Numeric array questions

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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!

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading