Home > database >  Calculation from specific value php array
Calculation from specific value php array

Time:09-26

Hello all i need help and want to get idea about my case

my case example : some name asigned powers like

  • jhon = 20
  • aliza= 30
  • rehana=40
  • adiba=50
  • black = 1000
  • white = 7500
  • red = 3500

when someone enter in input amount 50 then

  • i need output ( jhon and aliza )

if input amount is 70 then

  • output like this ( adiba and jhon )

if input is 4500 then

  • output need black and red

  • $input = "4500";

  • $groups_name = array("jhon"=>"20", "aliza"=>"30", "rehana"=>"40", "adiba"=>"50", "black"=>"1000", "white"=>"7500", "red"=>"3500");

  • how get output like this

  • Black and Red

CodePudding user response:

You could do it with just one for loop:

$groups_name = 
['jhon' => 20,
'aliza' => 30,
'rehana' => 40,
'adiba' => 50,
'black' => 1000,
'white' => 7500,
'red' => 3500];

$inputs = [50, 70, 4500];

function get_names($array, $input){
    foreach ($array as $name=>$value) {
        $target = abs($value - $input);
        if(in_array($target, array_values($array))){
            $pair = array_flip($array)[$target];
            echo "($name, $pair)";
            break;
        }
    }
}

Result:

get_names($groups_name, $inputs[0]); // (jhon, aliza)
get_names($groups_name, $inputs[1]); // (jhon, adiba)
get_names($groups_name, $inputs[2]); // (black, red)

CodePudding user response:

Please make it minor update:

$groups_name = 
['jhon' => 20,
'aliza' => 30,
'rehana' => 40,
'adiba' => 50,
'black' => 1000,
'white' => 7500,
'red' => 3500];

$inputs = [50, 70, 4500];

function get_names($array, $input){
    foreach ($array as $name=>$value) {
        $target = abs($value - $input);
        if(in_array($target, array_values($array))){
            $pair = array_flip($array)[$target];
            echo "($name, $pair)";
            break;
        }
    }
}

Result:

get_names($groups_name, $inputs[0]); // (jhon, aliza)
get_names($groups_name, $inputs[1]); // (jhon, adiba)
get_names($groups_name, $inputs[2]); // (black, red)
  • work only for two values
  • please make some change in it if input vale is 120 then
output ( Adiba   Rehana   Aliza ) 

if input vale is 1120 then

output ( Adiba   Rehana   Aliza   Black ) 
  • if input value is not match in given array

  • then show msg not fount

  •  Tags:  
  • php
  • Related