views:

47

answers:

4

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?

+2  A: 

Maybe ltrim?

$var = ltrim($var, '0');
robertbasic
+5  A: 

cast it to integer

$var = (int)$var;
AlberT
Missing semicolon :p
Lekensteyn
@Lekensteyn: Only if it is meant to be a statement instead of an expression.
Gumbo
it was not the entire line :) ehehhe
AlberT
is there similar function in javascript?
Happy
like (int) $var
Happy
of course, casting is a feature present in almost every language.In JS you can use parseInt()
AlberT
(int)$var is an statement, but assigning it to $var looks like a expression to me. Anyway, this is a oneliner, you don't need to add something else after it.
Lekensteyn
@Workinghard, `parseInt(var, 10)` or `1 * var` (my favorite :))
Lekensteyn
@Lekensteyn: `(int)$var` is an expression and an assignment is an expression too.
Gumbo
+2  A: 
$var = strval(intval($var));

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

Amber
+2  A: 
$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.

Lekensteyn