PHP strcmp结果int的含义

在php中,有一个内置函数strcmp可以比较两个字符串是否相同。


返回值是整数,如果第一个参数大于第二个,我得到> 0,如果没有< 0,如果相同的0。


所以我没有得到的部分是比较字符串作为数字。PHP是否将字符串转换为数字,如果可以,PHP如何转换?


$a = 'acorn';

$b = 'zebra';

var_dump( strcmp($a, $b) ); // -25 <- what's this number? seems like alphabetical position...nnn

我得到的数字真的不重要,我只接受它是多少吗?


开心每一天1111
浏览 166回答 2
2回答

慕工程0101907

查看PHP:strcmp doc:如果str1小于str2,则返回<0;否则,返回0。如果str1大于str2,则> 0;如果相等,则> 0。是的,您可以按原样使用它来比较您的字符串。但是,如果您想了解函数返回的数字,则取决于构成字符串的字符。在ASCII中:A = 65 <B = 66 <C = 67 ....因此,如果字符串不同,则一个字符串将大于另一个字符串。因此,您也可以使用简短的脚本轻松地对其进行测试:<?php$a='A';$b='B';$c='C';//Return -1 because $a is smaller than $b by one (65 < 66 )echo strcmp($a,$b);//Return -2 because $a is smaller than $c by two (65 < 67 )echo strcmp($a,$c);//Return -1 because $b is smaller than $c by one (66 < 67 )echo strcmp($b,$c);//Return 1 because $c is greater than $b by one (67 > 66 )echo strcmp($c,$b);//Return 2 because $c is greater than $a by two (67 > 65 )echo strcmp($c,$a);

手掌心

strcmp用于比较PHP中的两个字符串。如果结果大于0,则其平均变量1($ a)大于Var2($ b);如果返回结果小于0,则其平均$ b较大;如果结果等于0,则其两个字符串均等于彼此。$a="Hello world!";$b= "Hello world!";var_dump(strcmp($a, $b)); // result is 0$a = "Hello";$b = "Hello World";var_dump(strcmp($a, $b)); // Outputs: -6如果您想看到差异,可以使用它$a = 'some-content-here-example';$b = 'some-content-example';$asp = preg_split('//', $a, -1);$bsp = preg_split('//', $b, -1);$l1 = count($asp);$l2 = count($bsp);$length = $l1;if ($l2 > $l1) {&nbsp; &nbsp; $length = $l2;}$record = null;$x = null;for ($x = 0; $x < $length; $x++) {&nbsp; &nbsp; if ($a[$x] != $b[$x]) {&nbsp; &nbsp; &nbsp; &nbsp; if (!isset($a[$x])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $record.= $b[$x];&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $record.= $a[$x];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}echo $record;
打开App,查看更多内容
随时随地看视频慕课网APP