logo CodeStepByStep logo

by_age

Language/Type: PHP associative arrays collections

Write a function named by_age that accepts three parameters:

  1. an associative array where each key is a person's name (a string) and the associated value is that person's age (an integer)
  2. an integer for a minimum age, and
  3. an integer for a max age

Your function should return a new associative array with information about people with ages between the min and max, inclusive.

In your result associative array, each key is an integer age, and the value for that key is a string with the names of all people at that age, separated by "and" if there is more than one person of that age. The order of names for a given age should be listed in alphabetical order, such as "Bob and Carl" rather than "Carl and Bob". (You'll need to forcibly iterate over the parameter associative array in ABC order to achieve this.)

Include only ages between the min and max inclusive, where there is at least one person of that age in the parameter associative array. If the associative array passed is empty, or if there are no people in the associative array between the min/max ages, return an empty array.

For example, if an associative array named $ages stores the following key/value pairs:

{"Allison" => 18, "Benson" => 48, "David" => 20, "Erik" => 20, "Galen" => 15, "Grace => 25,
"Helene" => 40, "Janette" => 18, "Jessica" => 35, "Marty" => 35, "Paul" => 28, "Sara" => 15,
"Stuart" => 98, "Tyler" => 6, "Zack" => 20}

The call of by_age($ages, 16, 25) should return the following associative array:

{18 => "Allison and Janette", 20 => "David and Erik and Zack", 25 => "Grace"}

For the same associative array, the call of by_age(ages, 20, 40) should return the following associative array:

{20 => "David and Erik and Zack", 25 => "Grace", 28 => "Paul", 35 => "Jessica and Marty", 40 => "Helene"}
Function: Write a PHP function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.