tags:

views:

64

answers:

2

I have two arrays in php

$arrNum = array(1.7, 1.52, 0.01, 0.11);

$arrStr = array('1.7', '1.52', '0.01', '0.11');

Note that the second array is the same as the first one, except it has the values as strings.

Is it possible for a sorting or max/min operation to return a different result for the second array just because they are strings?

Can I always do an operation that requires value comparison on the string array and get the exact same result that I would have gotten if I had done it on the numeric version of the array?

+1  A: 

The other answer covers the cases of sort() and max() very well. For comparing items in php, there are two comparison operators that will treat things like 1.23 vs '1.23'differently: === and !==.

See http://php.net/manual/en/language.operators.comparison.php.

dreeves
+7  A: 

The documentation is clear, imo:

E.g. for sort():

This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.

And it takes a parameter to define how the values are treated:

Sorting type flags:

  • SORT_REGULAR - compare items normally (don't change types) <- this is the default
  • SORT_NUMERIC - compare items numerically
  • SORT_STRING - compare items as strings
  • SORT_LOCALE_STRING - compare items as strings, based on the current locale.

But it also has a warning:

Warning
Be careful when sorting arrays with mixed types values because sort() can produce unpredictable results.


Now for max():

Note: PHP will evaluate a non-numeric string as 0 if compared to integer , but still return the string if it's seen as the numerically highest value. If multiple arguments evaluate to 0, max() will return a numeric 0 if given, else the alphabetical highest string value will be returned.

and

When given a string it will be cast as an integer when comparing.


Update:

To answer your question: If you want to make absolutly sure that the sorting is correct, you know that the strings always contains numbers and you don't trust the string comparison, then specify to sort them numerically:

sort($array, SORT_NUMERIC);
Felix Kling