Page 115 - Open Soource Technologies 304.indd
P. 115
Unit 5: Strings
$o1 = 3; $o2 = “3”; if ($o1 == $o2) {echo (“== returns true<br>”) ;} if ($o1 === $o2) { echo(“=== Notes
returns true<br>”); } == returns true
The comparison operators (<, <=, >, >=) also work on strings:
$him = “Pradip”; $her = “Riya”; if ($him < $her) { print “$him comes before $her in the
alphabet.\n”; }Pradip comes before Riya in the alphabet
However, the comparison operators give unexpected results when comparing strings and numbers:
$string = “PHP Rocks”; $number = 5; if ($string < $number) { echo(“$string < $number”); } PHP
Rocks < 5
When one argument to a comparison operator is a number, the other argument is cast to a number.
This means that “PHP Rocks” is cast to a number, giving 0 (since the string does not start with a
number). Because 0 is less than 5, PHP prints “PHP Rocks < 5”.
To explicitly compare two strings as strings, casting numbers to strings if necessary, use the
strcmp( ) function:
$relationship = strcmp(string_1, string_2);
The function returns a number less than 0 if string_1 sorts before string_2, greater than 0 if string_2
sorts before string_1, or 0 if they are the same:
$n = strcmp(“PHP Rocks”, 5); echo($n); 1
A variation on strcmp( ) is strcasecmp( ) , which converts strings to lowercase before comparing
them. Its arguments and return values are the same as those for strcmp( ):
$n = strcasecmp(“Pradip”, “Pradip”); // $n is 0
Another variation on string comparison is to compare only the first few characters of the string.
The strncmp( ) and strncasecmp( ) functions take an additional argument, the initial number of
characters to use for the comparisons:
$relationship = strncmp(string_1, string_2, len); $relationship = strncasecmp(string_1, string_2, len);
The final variation on these functions is natural-order comparison with strnatcmp( ) and
strnatcasecmp( ), which take the same arguments asstrcmp( ) and return the same kinds of values.
Natural-order comparison identifies numeric portions of the strings being compared and sorts
the string parts separately from the numeric parts.
Table 5.5 shows strings in natural order and ASCII order.
Table 5.5: Natural Order versus ASCII Order
Natural order ASCII order
pic1.jpg pic1.jpg
pic5.jpg pic10.jpg
pig10.jpg pic5.jpg
pic50.jpg pic50.jpg
5.6.2 Approximate Equality
PHP provides several functions that let you test whether two strings are approximately equal:
soundex( ) , metaphone( ), similar_text(), and levenshtein( ).
$soundex_code = soundex($string); $metaphone_code = metaphone($string); $in_common =
similar_text($string_1, $string_2 [, $percentage ]); $similarity = levenshtein($string_1, $string_2);
$similarity = levenshtein($string_1, $string_2 [, $cost_ins, $cost_rep, $cost_del ]);
LOVELY PROFESSIONAL UNIVERSITY 109