
|
|
|||
Introduction to PHP ProgrammingBy PHP Catalyst2007-11-19
String Comparisons in PHP Comparing StringsString comparison is one of the most important part of strings related coding that you might do in your projects. It's very easy to understand but you will have to remember some key differences when using comparison operators while comparing strings. As usual we will begin with an example but in this case I will include 2 different examples in one set to show you the difference in output of comparison when using different comparison operators.
<?php //Example 1 with '==' comparison operatorAbove, in example #1, I have used '==' operator, which is evaluating if the value on right hand side is equal to value on left hand side. I guess, you expected the output to be 'False'? No, that's not the case. The output is 'True'. Strange? Not really! Always remember, when comparing strings, you should use '===' operator (strict comparison) and NOT '==' operator (loose comparison). When comparing an integer with a string, the string is converted to a number. And if you compare two numerical strings, they are compared as integers. Now try to replace $a == "Zero" with $a == "00" in the first example and see the results. Using built-in function to compare- strcmp()One other way of doing string comparison is using the PHP built-in function called strcmp(). This comparison is case-sensitive and the syntax of this function is:
strcmp ( string str1, string str2 )
It will return the following after comparison and your further processing should be based on this output:
Returns < 0 if str1 is less than str2
Returns > 0 if str1 is greater than str2 Returns 0 if they are equal Refer to the example below to see usage of strcmp():
<?phpFor case-insensitive comparison use the strcasecmp() function instead. Just replace the function name in above example and test the results. Alright, let's move on to String Manipulation.Tutorial Pages: » What can I do with PHP? » Popoular Features of PHP » Basics of PHP » Variables in PHP » Data Types in PHP » Expressions and Operators » Control Structures in PHP » Functions in PHP » Declaring Functions in PHP » Scope of a Variable » Built-in Functions in PHP » Handling Strings in PHP » Printing Strings in PHP » String Comparisons in PHP » Manipulating Strings in PHP » Arrays in PHP » Types of Arrays in PHP » Creating Arrays in PHP » Array Operations in PHP |
||||
| About the NetVisits, Inc Network | Write For Us | Advertise Copyright ©2007 NetVisits, Inc Network. All Rights Reserved. Privacy Policy. |
Visit other NetVisits, Inc. sites: |