Bululu
Bululu

Reputation: 575

Adding some numbers using PHP

Here is a situation:

race 1 = 7
race 2 = 3
race 3 = 1
race 4 = 2
race 5 = 6
race 6 = 2
race 7 = 7
race 8 = 3

The smaller the number the better since these are race positions. race number 1 MUST be added, regardless of it's magnitude and must be added to any 5 others that are selected on merit. So basically I want to use PHP to add up 6 of the best races out of the 8 and the 6 must include 1, regardless of whether it is among the best

I thoughtn of sorting the numbers by having them sorted from lowest to highest and adding the first 6. The problem is that if race 1, is not among the best 6, then this cannot work.

Any help will be appreciated, I am still thinking so I cannot provide anything in terms of what i have tried as everything is still at thought level!

Upvotes: 0

Views: 104

Answers (2)

Nick Maroulis
Nick Maroulis

Reputation: 487

<?php

    $race = array( 1 =>7, 2 => 3 );//etc
    $sum = $race[1];
    unset( $race[1] );

    sort( $race, SORT_NUMERIC );

    for( $i = 0; $i < 5; $i++ )$sum += array_pop( $race );

Upvotes: 1

Rob Allen
Rob Allen

Reputation: 17709

<?php
/* if manually creating the array */
$race1 = 7;  
$races = array("race2" => 3, "race3" => 1, "race4" => 2); //...

/* if the array is created programmatically (preferred */
$race1 = $races[0];
$races = array_pop($races); //drops first element and resets the index 

/* then.... */

asort($races);

$total = $race1;
for($i=0; $i<6; $i++)
{
    $total += $races[$i]; 
}

?>

Upvotes: 0

Related Questions