2

Problem:

I have a value that is set in $record, for instance 1.69. Then I have an array that contain different grades and values. I would like to compare $record against the highest value first to see if it is higher or equal to, if not go to the value below it, and so forth.

PHP code:

$record1 = '1.69';
$record2 = '2.90';
$record3 = '3.40';
$record4 = '3.80';

Array ($grades):

Array
(
    [G] => 2.8
    [VG] => 3.8
)

Scenario:

$record1 should be compared to the highest value in the array, this will return false. It will compare to the value below the highest value, which also will return false. If both return false then return the string 'U', otherwise return the key G or VG.

  • Record 1 should produce U.
  • Record 2 should produce G.
  • Record 3 should produce G.
  • Record 4 should produce VG.

Question:

I could do a lot of if-statements as a solution but I wonder if there is any clever way of doing this check in a better way?

3
  • How many record variables are there? Commented Jun 12, 2012 at 18:30
  • 1
    +1 for clearly defining the problem. Do you have the ability to create a $record array instead of independent variables? Commented Jun 12, 2012 at 18:34
  • There's always only going to be 1 $record variable. Commented Jun 12, 2012 at 18:49

4 Answers 4

1

Using simple logic:

$grades  = array('G' => 2.8, 'VG' => 3.8);
$records = array(1.69, 2.9, 3.4, 3.8);

foreach ($records as $v) {
    $res = ($v < $grades['G'] ? 'U' : ($v < $grades['VG'] ? 'G' : 'VG'));
    echo "$v = $res\n";
}

/*
1.69 = U
2.9 = G
3.4 = G
3.8 = VG
*/
Sign up to request clarification or add additional context in comments.

Comments

1

I would write a function that loops through your $grades array, sets the value of the result and breaks as soon as the value is bigger than the input.

Something like this (untested):

function returnGrade($record, $grades)
{
  $return = 'U';
  foreach  ($grades as $key => $value)
  {
    if ($record >= $value)
    {
      $return = $key;
    }
    else
    {
      break;
    }
  }
  return $return;
}

Comments

1

Firstly, try and sort the array in descending order.

Then, in a while loop, check if the initial array element (use key() function) is bigger or smaller, if FALSE, use next() function to move to next element and compare that.

The loop should end when your desired comparison returns TRUE.

Comments

0

you can do this way

first rotate in loop by number of records and check that value is in array or not by this function in_array()

if result found then get key by this function array_search("value_to_search","array_variable");

Hope this will helpful to you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.