note 80672 deleted from language.types.string by danbrown
| From: | danbrown@php.net | Date: | Tue, 17 May 2011 14:17:01 +0000 |
| Subject: | note 80672 deleted from language.types.string by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-179807@lists.php.net to get a copy of this message | ||
Note Submitter: topnotcher at mail dot uri dot edu
----
@qriz at example dot com
Numerical comparisons, such as <, > are simply _NOT_ valid on strings. Thus, before a
comparison can be made by a numerical comparison operator, the operands must be _casted_ to a
numerical type (either float or int). What I was attempting to say in my previous post is that
>, < are date-aware; the tests I included were examples, and not intended to represent the
full scope of my comparison.
"Works correctly since there is a comparing between strings. The comparisson is done on the
last number/letter (since thats the only thing that is difference in the string) and that is in this
case: the 9 and 8."
What you say here is mere assumption; a few quick tests show that this is indeed not the case. If
PHP indeed compares only the last character in the string, then the following assertion should be
false:
test.php:
<?php
$a = '2007-11-06 15:17:48';
$b = '2007-11-05 15:17:48';
var_dump($a > $b);
?>
mArIo@luigi ~ $: php test.php
bool(true)
Further, consider the following choices for $a and $b, which, as expected, demonstrate that the
<, > operators can indeed understand date formats:
<?php
$a = 'January 25th, 2008 00:23:37';
$b = 'January 24th, 2008 00:23:38'; // ($a > $b) === true, but 8
?>
If you remain unconvinced, consider what happens if I spell January incorrectly:
<?php
$a = 'January 25th, 2008 00:23:38';
$b = 'Janury 24th, 2008 00:23:37'; // ($a > $b) === false
?>
Looks like it can understand ISO 8601 date formats? (for more information, see http://en.wikipedia.org/wiki/ISO_8601)
Further investigation yields that this doesn't even work as it should:
<?php
$a = 'February 1st, 2008 00:23:38';
$b = 'January 25th, 2008 00:23:38';
var_dump($a > $b); //bool(false)
var_dump(strtotime($a)); //int(1201843418)
var_dump(strtotime($b)); //int(1201238618)
var_dump(strtotime($a) - strtotime($b)); //int(604800)
?>
Keeping $b constant and varying the month in $a shows that this comparison correctly interprets the
date with the following months: January,March,May,June,July,September,October,November.
Interestingly enough, these are all the months having the property that ord($a[0]) >= ord($b[0]).
<?php
var_dump('Z' > 'M'); //bool(true)
?>
Conclusion:
The <,> comparison operators definitely have functionality that is undocumented, including
date awareness; however, this functionality may not always work as expected and should not be
trusted for portability.