How to compare string in PHP

5 Answers

0 votes
$s1 = "abc";
$s2 = "ABC";
$r = strcmp($s1, $s2); // 'a' ascii is 95. 'A' ascii is 65. 'a' is bigger
echo $r . "<br>"; // 1
if ($r > 0)
    echo "s1 > s2";
else if ($r == 0)
         echo "s1 = s2";
     else
         echo "s2 > s1"; // s1 > s2


/*
run:
    
1
s1 > s2 

    
*/


answered Jun 12, 2014 by avibootz
edited Jul 19, 2016 by avibootz
0 votes
$s1 = "abc";
$s2 = "ABC";
if ($s1 > $s2)
    echo "s1 > s2";
else if ($s1 == $s2)
         echo "s1 = s2";
     else
         echo "s2 > s1"; // s1 > s2


/*
run:
    
s1 > s2 

    
*/


answered Jun 12, 2014 by avibootz
edited Jul 19, 2016 by avibootz
0 votes
$s1 = "abc";
$s2 = "ABC";
$r = strcasecmp($s1, $s2); // converts the strings to lowercase before comparing them
echo $r . "<br>"; // 0
if ($r > 0)
    echo "s1 > s2";
else if ($r == 0)
         echo "s1 = s2"; // s1 = s2
     else
         echo "s2 > s1";


/*
run:
    
0
s1 = s2 

    
*/


answered Jun 13, 2014 by avibootz
edited Jul 19, 2016 by avibootz
0 votes
$s1 = "abcd";
$s2 = "abcf";
$r = strncmp($s1, $s2, 3); // compare only the first 3 characters
echo $r . "<br>"; // 0
if ($r > 0)
    echo "s1 > s2";
else if ($r == 0)
         echo "s1 = s2"; // s1 = s2
     else
         echo "s2 > s1";


/*
run:
    
0
s1 = s2 

    
*/


answered Jun 13, 2014 by avibootz
edited Jul 19, 2016 by avibootz
0 votes
$s1 = "abcd";
$s2 = "ABCf";
$r = strncasecmp($s1, $s2, 3); // compare only the first 3 characters
echo $r . "<br>"; // 0
if ($r > 0)
    echo "s1 > s2";
else if ($r == 0)
         echo "s1 = s2"; // s1 = s2
     else
         echo "s2 > s1";


/*
run:
    
0
s1 = s2 

    
*/


answered Jun 13, 2014 by avibootz
edited Jul 19, 2016 by avibootz

Related questions

1 answer 109 views
1 answer 154 views
1 answer 224 views
1 answer 61 views
1 answer 101 views
101 views asked Jun 15, 2022 by avibootz
...