Home  >  Article  >  Backend Development  >  PHP function strcmp() that compares two strings (case sensitive)

PHP function strcmp() that compares two strings (case sensitive)

黄舟
黄舟Original
2017-11-04 09:10:253157browse

Example

Compare two strings (case sensitive):

<?php
echo strcmp("Hello world!","Hello world!");
?>

Definition and usage

strcmp() function compares two string.

Note: The strcmp() function is binary safe and case-sensitive.

Tip: This function is similar to the strncmp() function, except that with strncmp() you can specify the number of characters for each string to be compared.

Syntax

strcmp(string1,string2)
Parameters Description
string1 Required. Specifies the first string to compare.
string2 Required. Specifies the second string to be compared.

Technical details

PHP version: 4+

更多实例

实例 1

比较两个字符串(区分大小写,Hello 和 hELLo 输出不相同):

<?php
echo strcmp("Hello","Hello");
echo "<br>";
echo strcmp("Hello","hELLo");
?>

实例 2

不同的返回值:

<?php
echo strcmp("Hello world!","Hello world!"); // the two strings are equal
echo strcmp("Hello world!","Hello"); // string1 is greater than string2
echo strcmp("Hello world!","Hello world! Hello!"); // string1 is less than string2 
?>

以区分大小写的方式比较两个字符串 
Strcmp()函数对两个字符串进行二进制安全的比较,并区分大小写。其形式为: 
int strcmp ( string str1 , string str2 ) 
根据比较的结果将返回如下的一个可能值。 
•如果str1 和str2 相等则返回0 。 
•如果str1小于str2则返回-1 。 
•如果str1大于str2则返回1 。 
网站经常要求待注册的用户输入并确认他选择的密码,减少由于键入错误而生成不正确密码的可能性。因为密码通常是区分大小写的,所以strcmp()对于比较这两个密码是非常合适的: 

<?php 
$pswd = "supersecret"; 
$pswd2 = "supersecret"; 
if (strcmp($pswd,$pswd2) != 0) 
echo "Your passwords do not match!"; 
else 
echo "Passwords match!"; 
?>

注意,对于strcmp ( ) ,字符串必须完全匹配才认为是相等的。例如,Supersecret 不同于supersecret 。如果要以不区分大小写的方式比较两个字符串,可以考虑下面介绍的strcasecmp ()。 
关于这个函数,另一个容易混淆的地方是:两个字符串相等时要返回0 。这与使用==操作符完成字符串比较有所不同,如下: 
if ( $str1 = = $str2) 
两种方式目标相同,都是比较两个字符串,但要记住,它们返回的值却不同。 

实例代码: 

<?php 
echo strcmp("Hello world!","Hello world!"); 
//返回0 
?>
Return value: This function returns:
  • 0 - if the two strings are equal

  • ##8f029751ac12f19769820fc6523b37120 - if string1 Greater than string2

The above is the detailed content of PHP function strcmp() that compares two strings (case sensitive). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn