Working with PHP Octals and String conversions

前端 未结 5 747
暖寄归人
暖寄归人 2021-01-13 02:47

I\'m working with a database that has a bunch of serial numbers that are prefixed with leading 0\'s.

So a serial number can look like 00032432 or 56332432.

5条回答
  •  无人共我
    2021-01-13 03:38

    When you convert with (string) $number, you always get a string in decimal base, it doesn't matter if you write the number in octal mode or in decimal mode, an int is an int and it has not itself a base. It's his string representation that have to be interpreted with a base.

    You can get the octal string representation of a number in this way:

    $str = base_convert((string) 00032432, 10, 8);
    

    or giving the number in decimal rep:

    $str = base_convert((string) 13594, 10, 8);    
    

    or, more concisely but less clearly:

     $str = base_convert(00032432, 10, 8);
     $str = base_convert(13594, 10, 8);
    

    In the last the string conversion is made implicitly. The examples give all as result $str = "32432".

    base_convert converts a string representation of a number from a base to another

    If you want also the zeros in your string, you can add them with simple math.

    Hope this can help you.

提交回复
热议问题