Home > OS >  calculate array values by names and numbers sum php
calculate array values by names and numbers sum php

Time:06-25

Calculate values from array like enter input 500 then output is 200 is eqval jhon or 300 is eqval puppy the ans i need jhon and puppy need help am trying but not understand how to start

$input = '500';

    $array1 = array("200" => 'jhon',"300" => 'puppy',"50" => 'liza',
"150" => 'rehana',"400" => 'samra',"100" => 'bolda',);

need answer like this output

jhon,puppy and bolda,rehana

jhon and puppy have 500 values and bolda or rehana is also have 500 value i am trying but not now were to start

CodePudding user response:

So I'm going to go out on a guess here. (this sounds like cheating on homework lmao).

You need to output pairs of names where the two names add upto 500 (the input).

This probably wont be the most optimal solution, but it should be a solution that works?

$input = 500;

// using shorthand array formatting

$array1 = [
    200 => 'jhon',
    300 => 'puppy',
    50 => 'liza',
    150 => 'rehana',
    400 => 'samra',
    100 => 'bolda'
];

// create an array that holds names we have already processed.
$namesProcessed = [];

// loop over the names trying to find a compatible partner

foreach ($array1 as $points => $name) {
    
    foreach ($array1 as $pointsPotentialPartner => $namePotentialPartner) {

        // Don't partner with yourself...
        if ($name == $namePotentialPartner) {
            continue;
        }

        // Don't partner with someone that has already been processed.
        if (in_array($namePotentialPartner, $namesProcessed)) {
            continue;
        }

        // test if the two partners add up to the input
        if ($input == ($points   $pointsPotentialPartner)) {

           // if this is the first partner set, don't put in 'and'

           if (count($namesProcessed) == 0) {
               echo $name . ', ' . $namePotentialPartner;
           } else {
               echo ' and ' . $name . ', ' . $namePotentialPartner;
           }

           $namesProcessed[] = $name;
           $namesProcessed[] = $namePotentialPartner;
        }
    }
}

Hope this helps.

  •  Tags:  
  • php
  • Related