Search code examples
phpstringcomparestrcmp

wrong output when compare two string


i want to compare 2 ether address.

i tried trim, strcmo and replace null characters. but it doesn't work

here is my code:

<?php
$a='0x0c656968912fF22c17ABf5E190498034542CC475';
$b='0x0c656968912ff22c17abf5e190498034542cc475';
$a2 = str_replace("\0", "", $a);
$b2 = str_replace("\0", "", $b);

var_dump($a == $b);
var_dump($a2 == $b2);
var_dump(strcmp($a,$b));
var_dump(strcmp($a2,$b2));

it looks all of above var_dump should return true (and 0 in strcmp) but they dont! why?! is it a bug? how can i compare this string


Solution

  • You are experiencing what is demonstrated in the first example of PHP's documentation of the strcmp function here.

    Basically, the comparisons are case-sensitive. Therefore, strcmp does not return true because the character F in the 15 place of $a is uppercase, where as it is lowercase in $b.

    see below, highlighted by underscores:

    $a='0x0c656968912f_F_22c17ABf5E190498034542CC475';
    $b='0x0c656968912f_f_22c17abf5e190498034542cc475';
    

    Upon reconsideration, there are other instaces of case-mismatch between the two strings.