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条)

报告相同问题?

悬赏问题

  • ¥20 指导如何跑通以下两个Github代码
  • ¥15 大家知道这个后备文件怎么删吗,为啥这些文件我只看到一份,没有后备呀
  • ¥15 C++为什么这个代码没报错运行不出来啊
  • ¥15 一道ban了很多东西的pyjail题
  • ¥15 关于#r语言#的问题:如何将生成的四幅图排在一起,且对变量的赋值进行更改,让组合的图漂亮、美观@(相关搜索:森林图)
  • ¥15 C++识别堆叠物体异常
  • ¥15 微软硬件驱动认证账号申请
  • ¥15 GPT写作提示指令词
  • ¥20 根据动态演化博弈支付矩阵完成复制动态方程求解和演化相图分析等
  • ¥15 华为超融合部署环境下RedHat虚拟机分区扩容问题