skip to Main Content
<?php
$games = [
    ["Call of Duty", "Shooter", 59.95],
    ["Rocket League", "Sport", 19.95],
    ["Assassins Creed", "RP", 49.95]
];

?>

// i have an assignment where they want me to get the average string length from the titles and a average game price and echo it out like :

// echo "average price: €" . $averageprice;
// echo "average length of titles: " . $averagetitle

it needs to include:

  • number_format
  • for loop

i have tried numerous options but only got into coding for half a year now and havent really gotten into php. tried looking up different functions to use but couldnt get my head wrapped around it so i wonderd if the amazing coding community could heklp me out.

3

Answers


  1. Average is computed as $sum_of_values/$number_of_values, so you can use for loop to loop throught all the items and sum them up as for example $sum_of_prices += $current_item[2] and finally divide it by length of array (count($games)).

    For length of string, just find out length of string by strlen($current_item[0]) and add it to sum of lengths of titles like in prices. Finally divide it by length of array. You can use same loop for this.

    Login or Signup to reply.
  2. Not sure to have understand right your request,
    If games informations are always in the same position you can try something like this:

        <?php
    $games = [
        ["Call of Duty", "Shooter", 59.95],
        ["Rocket League", "Sport", 19.95],
        ["Assassins Creed", "RP", 49.95]
    ];
    
    $avg_name_lenght = 0;
    $avg_game_price = 0;
    
    foreach($games as $game ){
        $game_name_lenght = strlen($game[0]);
        $avg_name_lenght += $game_name_lenght;
        $game_price = $game[2];
        $avg_game_price +=$game_price;
    }
    
    $avg_name_lenght = $avg_name_lenght / count($games);
    $avg_game_price = $avg_game_price / count($games);
    
    echo "<p>average price: €" . $avg_game_price."</p>";
    echo "<p>average length of titles: " . $avg_name_lenght."</p>";
    
    ?>
    
    Login or Signup to reply.
  3. Try something like this.
    It includes a for loop en the number_format function:

    function getAveragePrice($array) {
        $sum = 0;
        for($i = 0; $i < count($array); $i++) {
            $sum += $array[$i][2];
        }
    
        return number_format($sum / count($array), 2);
    }
    
    function getAverageLength($array) {
        $sum = 0;
        for($i = 0; $i < count($array); $i++) {
            $sum += strlen($array[$i][0]);
        }
    
        return number_format($sum / count($array), 2);
    }
    
    $averageprice = getAveragePrice($games);
    $averagetitle = getAverageLength($games);
    
    echo "average price: €" . $averageprice . "<br>";
    echo "average length of titles: " . $averagetitle . "<br>";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search