Snappysites
Snappysites

Reputation: 843

PHP Max() function not working when value hits 10

So I am having a bit of an issue with this code snippet... Here are my variables:

$total_one = ''.$total_one_section.' One'; 
$total_two = ''.$total_two_section.' Two';
$total_three = ''.$total_three_section.' Three';
$highest_total_level = max($total_one,$total_two ,$total_three);

The current totals are:

10 One
4 Two
3 Three

This means that the code should return 10 One but it is returning 4 Two for some reason. I have noticed that if I change the value of One to 9 so: 9 One then it returns as it should, 9 One as the highest. It only seems to stop functioning correctly when the value hits 10? Does anybody have any idea why this might be happening?

Upvotes: 0

Views: 565

Answers (3)

raina77ow
raina77ow

Reputation: 106453

See, PHP's max() is an omnivore: it allows arguments of any type, comparing using the standard comparison rules with type juggling on demand.

As all the values you passed into it are strings, they are compared on char-by-char basis (so called lexical comparison), starting from the first one. As character 4's code point is higher than 1's, '4 Two' is greater than '10 One'.

There are many ways to solve this; the key is storing the original (numeric) values in one way or another. One possible approach is suggested in @Geoffrey's answer - use numbers as key, and their 'tails' as values of this array, then just apply max over array_keys():

$lines = array(
  '4' => 'Two',
  '3' => 'Three',
  '9' => 'Four',
  '100' => 'One',  
);

$max_key = max(array_keys($lines));
echo $max_key . ' ' . $lines[$max_key]; // 100 One

Upvotes: 2

Xue Fang
Xue Fang

Reputation: 108

What PHP is trying to do is to sort your number as string, you might prefer something like :

$numbers = array(

  10 => "one",
  4 => "two",
  3 => "three"

)

Then mix with something like that Hightest value of an associative array

Upvotes: 0

Phiter
Phiter

Reputation: 14982

You are comparing strings, 4 Two starts with 4 while 10 One starts with 1. That's what MAX is comparing. You should compare $total_two_section, $total_one_section and $total_three_section, since they are integers.

Upvotes: 1

Related Questions