728x90

문자열 비교 strcmp

strcmp(string1,string2);


결과값

0 : 두 문자열이 같다.

<0 : string1 is less than string2

>0 : string1 is greater than string2


<?php
$mailing = $row['mailing'] = 1; // DB에서 읽어온 값이라 가정
if(!strcmp($mailing,"1")) {
  $mailing = "가입";
} else if(!strcmp($mailing,"2")) {
  $mailing = "완료";
} else if(!strcmp($mailing,"3")) {
  $mailing = "추가";
} else {
  $mailing = "거부";
}
echo $mailing;
?>


strcmp 를 잘못 사용하면 원하지 않는 결과가 나올 수 있음에 유의하자.

if(0 == NULL){
    echo "True";
} else {
    echo "False";
}

결과는 True 를 반환한다.


if(0 === NULL){
    echo "True";
} else {
    echo "False";
}

결과는 False 를 반환한다.

PHP에서 조건문을 느슨하게 비교하면 원하지 않는 결과가 나올 수 있다.


strcmp는 string(문자열)을 비교하라고 되어 있다.

그런데 문자열 대신 배열을 넣고 비교하면 어떤 결과가 나올까?


$a = Array("a");
$b = 'password';

if (!strcmp($a, $b)){
  echo "Strings are same !";
} else {
  echo "Strings are different";
}

결과

Warning: strcmp() expects parameter 1 to be string, array given in C:\AutoSet9\public_html\11.php on line 5
Strings are same !

보시는 바와 같이 $a 와 $b는 다음에도 불구하고 경고 메시지는 나오지만 결과는 동일하다고 출력한다.


$a = Array("a");
$b = 'password';

if (strcmp($a, $b) === 0){
  echo "Strings are same !";
} else {
  echo "Strings are different";
}

와 같이 해주면 경고메시지는 출력하지만 결과는 다르다고 출력한다.

Warning: strcmp() expects parameter 1 to be string, array given in C:\AutoSet9\public_html\11.php on line 5
Strings are different


하나더 살펴보자.

육안으로 확인하면 두개의 문자열은 서로 다르다. 하지만 결과는 느슨비교를 해서 True를 반환한다.

$something = 0;
echo ('password' == $something) ? 'True' : 'False';


따라서 === 비교를 해주어야 한다.

$something = 0;
echo ('password' === $something) ? 'True' : 'False';


$something = 0;
echo ('1' == $something) ? 'True' : 'False';
이 경우에는 같은 정수를 비교하므로 == 를 사용해도 False 를 반환한다.

문자열과 숫자를 비교시 느슨비교를 하면 엉뚱한 결과가 나옴을 확인할 수 있다.


<?php
$val = 20;
if($val === '20'){
    echo '결과는 동일하다';
} else {
    echo '$val은 정수형, "20"은 문자열형이다.';
    echo '<br />결과는 다르다.';
}
?>


Don't use == in PHP. It will not do what you expect.

Even if you are comparing strings to strings, PHP will implicitly cast them to floats and do a numerical comparison if they appear numerical.

느슨한 비교를 하면 원하지 않은 결과가 나올 수 있음에 유의하자!


블로그 이미지

Link2Me

,