Incrementing a string and retaining whatever amount of leading zeros there is

How can I get this to work:

$q = '0004';

echo ++$q; // outputs 5 instead of 0005

$q is pulled from a db, and can have any amount of leading zeros, so I can't use str_pad or sprintf (unless I count the number of zeros, but that's messy if there is a simpler way)

Thanks!

1 answer

  • answered 2018-05-16 05:53 statistic

    $q='1'.$q;
    $q++;
    $q= substr($q, 1);
    

    I think it works.

    Edit: It will be a string.