0

I am doing the exercise in Learning PHP5 from Oreilly and the task is to caculate to total population of states (with a limited number of cities).

I have created a multidimensional array with states and then inside cities but unlike what is proposed as solution in the book, I am trying to use the sum_array() function to calculate, for each state, the population.

My logic must be somehow wrong as I array_sum doesn't seem to know which array to use (I triple-checked the names and I wrote the good array name). What am I missing?

Here's what I have so far:

$population = array ( 
    'NY' => array('New York' => 8008278),
    'CA' => array('Los Angeles' => 3694820, 'San Diego' => 1223400),
    'IL' => array('Chicago' => 2896016),
    'TX' => array('Houston' => 1953631, 'Dallas' => 1188580, 'San Antonio' => 1144646),
    'PA' => array('Philadelphia' => 1517550),
    'AZ' => array('Phoenix' => 1321045),
    'MI' => array('Detroit' => 951270)
);

print '<table><tr><th>State</th><th>City</th><th>Population</th></tr>';

foreach ($population as $state => $city_info) {
    foreach ($city_info as $city_name => $city_population) {
    print "<tr><td>$state</td><td>$city_name</td><td>$city_population</td></tr>";
    }
    print "<tr><td></td><td>{$state}'s total population</td><td>array_sum($city_info)</td></tr>";
}

print "<tr><td></td><td></td></tr>";

1 Answer 1

4

You forgot about function inside quotes. Must be something like this.

print "<tr><td></td><td>{$state}'s total population</td><td>".array_sum($city_info)."</td></tr>";
Sign up to request clarification or add additional context in comments.

1 Comment

Why not? Its ooutput something like this CA Los Angeles 3694820 CA San Diego 1223400 CA's total population 4918220

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.