PHP string compare
In this article I will show you how you can use PHP string compare functions.
Step 1 - PHP string compare solutions
PHP string compare
Time to time you want to compare various strings and control your script execution regarding the result. You can do this in more ways. The most simple way to use the compare operator (==) as follows:
Code:
<?php $str1 = "Test"; $str2 = "Test"; ?>
However you can use PHP built in functions as well like strcmp and strcasecmp. These functions make a binary safe string comparison where the strcasecmp is a case-insensitive version. With this functions you can also decide which string is greater or smaller as it returns < 0 if STR1 is less than STR2 > 0 if STR1 is greater than STR2, and 0 if they are equal. So you can use these functions like this:
Code:
<?php $str1 = "Test"; $str2 = "Test"; $str3 = "Apple"; $str4 = "Zebra"; ?>
Sometimes it can happen that the strings seems to be equal but the comparison reports that they are different. The most common problem in this case that there are some spaces before or after the relevant text. This results that the strings are different. To solve this problem it make sense to use the PHP built in trim function to remove all unwanted spaces like this:
Code:
<?php $str1 = "Test"; $str2 = " Test "; ?>
Tags: php string compare, string compare, php string, string, compare
| PHP string compare - Table of contents |
|---|
| Step 1 - PHP string compare solutions |