PHP remove first zeros

2019-03-24 02:17发布

问题:

Want to remove all 0 placed at the beginning of some variable.

Some options:

  1. if $var = 0002, we should strip first 000 ($var = 2)
  2. if var = 0203410 we should remove first 0 ($var = 203410)
  3. if var = 20000 - do nothing ($var = 20000)

What is the solution?

回答1:

cast it to integer

$var = (int)$var;


回答2:

Maybe ltrim?

$var = ltrim($var, '0');


回答3:

$var = ltrim($var, '0');

This only works on strings, numbers starting with a 0 will be interpreted as octal numbers, multiple zero's are ignored.



回答4:

$var = strval(intval($var));

or if you don't care about it remaining a string, just convert to int and leave it at that.



回答5:

Just use + inside variables:

echo +$var;


回答6:

Carefull on the casting type;

var_dump([
    '0014010011071152',
    '0014010011071152'*1,
    (int)'0014010011071152',
    intval('0014010011071152')
]);

Prints:

array(4) {
    [0]=> string(16) "0014010011071152"
    [1]=> float(14010011071152)
    [2]=> int(2147483647)
    [3]=> int(2147483647)
}


回答7:

Multiple it by 1

$var = "0000000000010";
print $var*1;  

//prints 10