doudou3213 2014-07-25 13:51
浏览 41
已采纳

你为什么在PHP中有一个字符串> ='0'的条件?

As part of an integration against a third party service I need to calculate a check digit. I have been given a PHP snippet to show the algorithm but I need to implement it in pl/sql. The PHP snippet (taken from here) is:

function arvutaViitenumber($nr){
     $nr = (string)$nr;
     $kaal = array(7,3,1);
     $sl = $st = strlen($nr);
     $total = 0;
     while($sl > 0 and substr($nr, --$sl, 1) >='0'){
         $total += substr($nr, ($st-1)-$sl, 1)*$kaal[($sl%3)];
     }
     $kontrollnr = ((ceil(($total/10))*10)-$total);
     return $nr.$kontrollnr;
}

I understand most of it except the substr($nr, --$sl, 1) >='0'condition in the loop. There are two things I do not understand about this:

  1. The main body of the loop takes each digit in order from the start. Why then have a condition where the loop exits before processing the nth digit from the start based on the state of the nth digit from the end?

  2. When comparing a single-character string as greater or equal string '0' can the condition ever be false? In my tests it is always true, even if the string compared is a character not a number.

Question 1 is more of accademic intrest. My real interest is question 2 and how I will implement this check in the pl/sql version (or if I even need to?)

  • 写回答

3条回答 默认 最新

  • dongpang1232 2014-07-25 14:01
    关注

    1. Well, think how the reverse would go.

     $st = strlen($nr);
     $sl = $total = 0;
     while($sl < strlen($nr) and substr($nr, ++$sl, 1) >='0'){
    

    Notice the strlen in the while loop - bad practice. Although in PHP it's fast, in most programming languages this is horrible for performance. The alternative would be to use another variable, which would be reduntant.

    So the best option for both lazyness and performance is to start from the end.

    2. As far as I can tell, the only purpose of that string comparison is to make sure the position in the ASCII table is higher or equal to '0' ASCII no. 48). First, check the http://www.asciitable.com/

    Then take a look at the following tests I did:

    var_dump(' ' >= '0'); // false // space has ASCII no 32
    var_dump('(' >= '0'); // false // ASCII no 47
    var_dump('A' >= '0'); // true // ASCII no 65
    var_dump('[' >= '0'); // true // ASCII no 71
    

    So it's almost an alphanumeric test, as @mudasobwa mentioned.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站