Boram Lamppa
Boram Lamppa

Reputation: 23

How to get this value by using For loop in array php

<?php
    $citySurvey = array("London", "Paris", "Rome", "Rome", "Paris",
    "Paris", "Paris", "London", "Rome", "Rome",
    "Paris", "London", "Paris", "London", "London",
    "London", "Paris", "London", "Paris", "Rome");

    print ("<h1>CITY SURVEY RESULTS</h1>");
    print ("<table border = \"1\">");
    print ("<tr><td>cities</td><td>Counts</td></tr>");


    print ("</table>");

?>

I need to use For Loop to get this array code works. I need to get the number of people who chose each of these cities.

I need to display the result in the table. The first column is the name of cities and second is counts.

Thank you for your help.

Upvotes: 1

Views: 56

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

1.Always try to separate HTML from PHP as much as possible.

2.You need to use array_count_values() and foreach() for desired output

Code needs to be like below:-

<?php
    $citySurvey = array("London", "Paris", "Rome", "Rome", "Paris",
    "Paris", "Paris", "London", "Rome", "Rome",
    "Paris", "London", "Paris", "London", "London",
    "London", "Paris", "London", "Paris", "Rome");

    $count_city_array = array_count_values($citySurvey);
?>
<h1>CITY SURVEY RESULTS</h1>
<table border="1">
    <tr>
        <td>cities</td>
        <td>Counts</td>
    </tr>
<?php

foreach($count_city_array as $key=>$val){?>
    <tr>
        <td><?php echo $key;?></td>
        <td><?php echo $val;?></td>
    </tr>

 <?php } ?>
</table>

Output on my local screen:- https://prnt.sc/j6u4ay

Upvotes: 1

Related Questions