Borna Borna - 1 year ago 132
PHP Question

Two different special characters are equal

I'm trying to compare 2 different special characters, but they are equal when I compare them.

$char1= "";
$char2= "";

echo mb_detect_encoding($char1, 'UTF-8', true); // 'UTF-8'
echo mb_detect_encoding($char2, 'UTF-8', true); // 'UTF-8'

if($char1 == $char2) // TRUE
echo strcmp($char1, $char2); // 0



PhpStorm 9.0.2

What can I do to make a valid comparison?

Thank you.

Answer Source

What can I do to make a valid comparison?

Updated Solution

Perhaps we're looking at this the wrong way. The problem may have nothing to do with PHP, but be about your code editor instead. Perhaps the editor is registering both chars as the same when you enter them, so PHP doesn't see any difference. Here is what you can do:

  1. Save each char in a file by itself, using an editor that recognizes the character, such as Wordpad
  2. Load the character in PHP with $char=file_get_contents('path/to/char.txt')
  3. Now that we've bypassed your code editor entirely, compare the two. If they're different, your editor might be to blame.

Original Solution

You could try to convert your characters to their ASCII values and compare the values instead of the characters

$ordUTF8 = function($char){
    list(, $ord) = unpack('N', mb_convert_encoding($char, 'UCS-4BE', 'UTF-8'));
    return $ord;
$char1= "";
$char2= "";
// 61656 and 61558 in my testing
$isEqual = $ordUTF8($char1)===$ordUTF8($char2);

Live demo. This solution was inspired by this accepted answer

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download