How to Compare Functions for Strings in PHP
In Hypertext Preprocessor (PHP), a string is a variable consisting of multiple characters. These characters can be letters, numbers, or any other supported special characters. Sometimes, it may be useful to compare two different strings. In order to do this in PHP, you must use a special function. The PHP strcmp( ) function is a built-in function that compares two different strings. You can then use the result of this comparison in conjunction with other tasks.
Instructions
-
-
1
Begin your PHP script with "<?php".
-
2
Store your strings as separate variables. For example:
<?php
$tea = "tea";
$coffee = "coffee";
-
-
3
Use the strcmp( ) function to compare your strings. Specify each string as a parameter, and store the output as a variable:
$s = strcmp($tea, $coffee);
This stores the output of the string comparison in variable $s. The strcmp returns a negative value if the first string is less than the second, zero if they are equal, and a positive value if the first is greater than the second. This is based on the alphabetic position of the letters in each string. In this case, because "t" comes after "c" alphabetically, the function will return a positive value.
-
4
Close your PHP script with "?>".
-
1
Tips & Warnings
The result of the strcmp( ) function is useful in the context of functions and loops. You can execute different tasks based on the result of the function.
References
- Photo Credit Thinkstock Images/Comstock/Getty Images