is it possible to convert 09 to 9 by any function?if yes,please tell me.It is required to me.Thank you.

Dani AI

Generated

Two quick fixes already posted by and are the usual answers: force a numeric conversion (so the string becomes an integer) or cast it. Below are a few practical alternatives, edge cases, and safe snippets you can apply depending on whether you want a numeric value or a cleaned string.

If you need a numeric value for arithmetic, use an explicit conversion function (fast and predictable). Example:

$number = intval($str, 10);

Use floatval() if you need decimals preserved. See the PHP docs on type conversion for details: Type juggling and intval().

If you only want to remove leading zeros from a string (keeping it a string), ltrim() or a regex are handy. ltrim() is simple but be sure to handle the case where the string becomes empty (all zeros):

$trimmed = ltrim($str, '0');
if ($trimmed === '') { $trimmed = '0'; }

A regex that preserves a single zero looks like this:

$trimmed = preg_replace('/^0+(?!$)/', '', $str);

See ltrim() and preg_replace().

Cautions and tips: trimming or converting will drop information useful for things like ZIP codes or phone numbers—keep those as strings. Converting stops at the first non-digit (so "09abc" becomes 9, while "abc09" becomes 0). Trim whitespace first if input may include it. Finally, remember that integer literals written in PHP source with a leading zero are octal (a different concept than converting a string); see integer literals.

Recommended Answers

All 3 Replies

Sure! Easiest way to convert a string into a number is just to add 0 to it!
So: 09+0=9.
I do this all the time when I know I have a string that is actually a number and want to use it as such. This also works in perl, too!
But you must be cartain that this will always be a numeric string, or errors will result.

$val = (int)'09'; works too.

It is working.Thank you for your response.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.