briangallagher
briangallagher

Reputation: 539

PHP how to invert a scale of numbers

Say I have a dataset, each element has an associated "score".

eg:
Banana - 5
Apple - 3
Pear - 2

I want to invert the scale so that :
All 5's become 1's
All 4's become 2's
All 3's become 3's
All 2's become 4's
All 1's become 5's

So I'd end up with
Banana - 1
Apple - 3
Pear - 4

I'm struggling to find a graceful solution that doesn't involve creating a map.

Upvotes: 2

Views: 1543

Answers (4)

Marcio J
Marcio J

Reputation: 780

Formula for other scale ranges:

$new = $rangeMax + $rangeMin - $old

Upvotes: 0

Yoshi
Yoshi

Reputation: 54649

Try:

$initial = array(
  'Banana' => 5,
  'Apple' => 3,
  'Pear' => 2,
);

$max = max($initial);
foreach ($initial as &$val) {
  $val = $max + 1 - $val;
}

print_r($initial);

Upvotes: 1

Mchl
Mchl

Reputation: 62387

The formula is $new = -$old + 6. Just use it with array_map

Upvotes: 3

Bjoern
Bjoern

Reputation: 16304

Just loop through all elements, and calculate the new "score" like this:

$score_new = ($score_old - 6) * (-1);

Upvotes: 0

Related Questions