30

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?

7 Answers 7

93

Just cast it to integer

$var = (int)$var;
Sign up to request clarification or add additional context in comments.

15 Comments

@Lekensteyn: Only if it is meant to be a statement instead of an expression.
@Workinghard, parseInt(var, 10) or 1 * var (my favorite :))
I really think the "pseudo code" in the question was referring to strings .. an octal number IS already an int .. the representation is not influent on the value. Your test should be on $var = '0131';, a string.
Watch your step. That only works for integers! If the value is a decimal number, then the decimal is removed. Therefore, I think ltrim is the better idea to remove leading zeros (as the title of the question is)
true, but the question was for integers ;)
|
36

Maybe ltrim?

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

1 Comment

Yes, this way we don't affect possible decimal places.
16
$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.

Comments

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

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

Comments

5

Just use + inside variables:

echo +$var;

6 Comments

Interesting. Can you post a link to the relevant documentation?
Really I have no reference! but works like a charm! change strings to numbers and remove all unnecessary zero and change string to number.
A + unary operator acts on numbers, so you are doing an implicit cast ... bad code as it hides the logic with no other advantages IMHO ...
Nice try, it work in Javascript but with PHP, you just cast the var :-D
Documentation : it is called "identity" → php.net/manual/en/language.operators.arithmetic.php
|
2

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

1 Comment

for [2]=> int(2147483647) [3]=> int(2147483647) its integer overflow , so results will not be expected if value is more than max integer limit i.e. 2,147,483,647 (or hexadecimal 7FFFFFFF16)
2

Multiply it by 1

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

//prints 10

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.