0

In PHP when we do a substr() such that the resultant string should be something like 0004, PHP automatically removes the leading 0s and just gives 4.

I want to avoid this behavior. I want the leading zeroes to stay there. How can I enforce that?

Forexample the following snippet prints 4.

echo substr("100041", 1, 4); 

How can I force it to print 0004?

Shy
  • 542
  • 8
  • 20
  • 2
    What is your PHP version? Because it is running fine in PHP 7.2 – akshaypjoshi Sep 02 '18 at 14:15
  • 1
    *"PHP automatically removes the leading `0`s and just gives `4`."* -- no, it doesn't. Check it yourself: https://3v4l.org/F3DdR – axiac Sep 02 '18 at 14:16
  • @akshaypjoshi 7.2. This is weird. – Shy Sep 02 '18 at 14:17
  • 2
    Does this exact code omit the zeroes? Just wondering if there's more code that impacts this, maybe something treating the value as an integer or something. – BizzyBob Sep 02 '18 at 14:19
  • @BizzyBob The exact code is `$alpha = hexdec(substr($bravo, 6, 4));`. Yeah `hexdec()` is treating it as integer and yes I am printing after `hexdec()` is applied. Now what's the solution. How do I solve this? I need `0003` as a result – Shy Sep 02 '18 at 14:28
  • 1
    Could use `sprintf` or `str_pad`; https://stackoverflow.com/questions/1699958/formatting-a-number-with-leading-zeros-in-php – BizzyBob Sep 02 '18 at 14:32

3 Answers3

0

Who said? Php doesn't remove 0 in string...

enter image description here

BadPiggie
  • 5,471
  • 1
  • 14
  • 28
0

Anyway create a own function..

<?php

function substring($data,$from,$length){

    $sub = "";
    $data = str_split($data);
    $i = 0;
    $l = 1;
    foreach($data as $letter){

        if($i >= $from && $l <= $length){

            $sub .= $letter;
            $l = $l+1;
        }

        $i = $i+1;
    }

    return $sub;
} 

echo substring("100041", 1, 4);

?>
BadPiggie
  • 5,471
  • 1
  • 14
  • 28
0

It doesn't:

var_dump(substr("100041", 1, 4));
string(4) "0004"

(online demo)

As per documentation this is a 100% string function. It doesn't handle numbers in any special way.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360