Home > Net >  Average from Array - PHP
Average from Array - PHP

Time:12-15

<?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.

CodePudding user response:

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.

CodePudding user response:

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>";

?>
  • Related