Comparing Strings

String comparing in PHP is one of the most important part of our projects.

Comparing strings seems like an easy task but you will have to remember some key differences when using comparison operators == (equal operator), >= (greater than or equal to), <= (less than or equal to), <> (not equal), > (greater than), < (less than)etc. These operators implicitly convert the type of a string.

See example:

<?php

    $a 
2//a PHP integer

    
$b '2'//a PHP string

    
var_dump($a == $b); //results bool(true)

    
var_dump($a <> $b); //results bool(false)

    
var_dump($a >= $b); //results bool(true)

    
var_dump($a <= $b); //results bool(true)

?>

PHP is a loosely typed language and automatically converts the variable to the correct data type, depending on its value. In above example, we compared an integer value $a with a string value $b, PHP automatically converts the string value $b into the integer value. Always remember 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. See example:

<?php

    $a 
2//a PHP integer

    
$b '2PHP'//a PHP string

    
var_dump($a == $b); //results bool(true)

    
var_dump($a <> $b); //results bool(false)

    
var_dump($a >= $b); //results bool(true)

    
var_dump($a <= $b); //results bool(true)

?>

Still getting the same results... strange? Didn't you expecting the false result of $a==$b? Always remember, when comparing strings, you should use === identical operator, === also called type checking operator. Identical operator === compares the values, types and return true if both values and types are same.

<?php

    $a 
2//a PHP integer

    
$b '2PHP'//a PHP string

    
var_dump($a === $b); //results bool(false)

    
var_dump($a !== $b); //results bool(true)

?>

Contents and Related Tutorials

  1. A list of PHP Comparison Operators with examples
  2. Assignment = vs Equal == vs Identical === Operators
  3. Basics of Strings Comparing
  4. Case Sensitive: Compare strings with strcmp() function
  5. Case Insensitive strings comparison with strcasecmp() function