Hi all

for example I want to remove the leading 0 from this var
$var = 01

how would I do this ?
at the moment im using
ereg_replace("0", "", $test['2']);

but this deletes all the 0 zeros.

so

$var = 30;

becomes 3 which i dont want,

thanks all.

    $var = "01";
    echo substr($var,1);
    
      laserlight wrote:

      Try using [man]ltrim/man, e.g.

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

      thank you 🙂

        If you want all leading zeros removed:

        $value = 003;

        $value = intval($value);

          4 years later
          richie;10679123 wrote:

          If you want all leading zeros removed:

          $value = 003;

          $value = intval($value);

          It may be just as good slightly faster to use typecasting instead of function

          $value = (int)$value; //typecasting instead of a function.

          For a discussion on the topic, try searching google for "php intval vs int"

          Also, if you're running a mission critical app, then remember php int limit is 2,147,483,647, and any integer above this will give you exactly 2,147,483,647. So, you may want to catch it by using something like:

          if ($value > 2,147,483,646) {
          //take any necessary steps, but don't continue with the script since
          // chances are it will all be reported as 2,147,483,647
          exit("Integer values larger then 2,147,483,646 are all reported as 2,147,483,647 and will be inaccurate");
          }

          Good luck.

            7 years later
            blueshadow wrote:

            Thank you so much.

            Wow ... history much? 😃

            Were you dealing with this same issue?

            If I correctly understand the original poster's purpose, [man]number_format/man would be canonical function for this use case. If you wish to ensure a certain type of variable, you wrap your number_format() call in another function, such as intval().

              And I feel the need to reply to this resurrected thread that there is a difference between...

              $var = 01;  // integer 1 from the octal integer notation
              // and
              $var = "01";  // string "01"
              
              $ php -r '$var = 01; var_dump($var);'
              int(1)
              

              And lastly, it's supposedly more efficient to cast it than to use the *_val() functions, e.g.:

              $ php -r '$var = "01"; echo (int) $var; echo PHP_EOL;'
              1
              

              (Yes, I'm just goofing off before breaking for lunch.)

                Another difference is that intval accepts a second argument for base, which may be important when using strings:

                php -r 'var_dump((int) "0123", intval("0123", 8));'
                
                int(123)
                int(83)
                
                  Write a Reply...