Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP remove first zeros

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?

like image 426
James Avatar asked Aug 25 '10 07:08

James


5 Answers

cast it to integer

$var = (int)$var;
like image 88
drAlberT Avatar answered Nov 01 '22 00:11

drAlberT


Maybe ltrim?

$var = ltrim($var, '0');
like image 37
robertbasic Avatar answered Nov 01 '22 00:11

robertbasic


$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.

like image 21
Lekensteyn Avatar answered Oct 31 '22 23:10

Lekensteyn


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

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

like image 5
Amber Avatar answered Oct 31 '22 23:10

Amber


Just use + inside variables:

echo +$var;
like image 5
poostchi Avatar answered Oct 31 '22 22:10

poostchi