Comparing Strings

Comparison operators can be used on text strings, but with this type of data the comparison works slightly differently to how it does with numeric values. Two strings are compared based on their ASCII sort order, as in this example:

"cat" < "dog"

The above comparison returns a value of True, because the first character of the first string (“c”) is lower in the alphabet than the first character in the second string (“d”). If the first characters were the same, the operator would compare the next character in both strings, and so on until the condition is either proven or the end of the string is reached.

Equality of strings can be tested using the equality operator, as in examples below.

"cat" = "cat"
"cat" = "cats"

The equality comparison will only return True if the two strings are identical, meaning that only the first of the above two examples returns True. In the second example, because the first three characters are the same the sort order would be close, but they are not identical. The longer string will always come after the shorter one, and hence the following expression does equate to True:

"cats" > "cat"

Another thing to bear in mind is that comparison of text is case sensitive. Due to this, the following expression equates to False:

"Cat" = "cat"

Because capital letters have a lower sort position than their lower case equivalents, the following expression is True:

"Cat" > "cat"

One important point to note about the Expression Engine’s comparison rules for strings is that any wholly numeric value within string quotes will be interpreted as the number itself. So, for example:

"3.5" – 0.5 = 3

The above expression is true in the same way it would be if “3.5” were not written in quotes. This is useful when it comes to extracting numeric values from strings, which we will cover later in this guide.

 

<< Previous: Less Than Or Equal To ( ≤ ) and Greater Than Or Equal To ( ≥ ) | Next: Comparison Operator Precedence >>