0
<?php

$str = "02";
$int = 1;

$result = $str-$int;

echo $result // 1

?>

But I need result = 01

Don't tell me "0".$str-$int;

l2aelba
  • 21,591
  • 22
  • 102
  • 138

4 Answers4

5
<?php
$str = "02";
$int = 1;

printf('%02d', $str-$int);

or

<?php
$str = "02";
$int = 1;

$result = sprintf('%02d', $str-$int);
// do something with $result here

see http://docs.php.net/manual/en/function.sprintf.php

VolkerK
  • 95,432
  • 20
  • 163
  • 226
4

try

printf("%02d",$str-$int);

The explanation of the numerous formatting possibilities of printf are explained in the sprintf docs

fvu
  • 32,488
  • 6
  • 61
  • 79
3
<?

$str = "02";
$int = 1;

echo sprintf("%02d", (int)$str - $int);

?>
skurton
  • 337
  • 2
  • 9
  • `echo sprintf()` is an "antipattern". There is absolutely no reason that anyone should ever write `echo sprintf()` in any code for any reason -- it should be `printf()` without `echo` every time. – mickmackusa Apr 09 '22 at 02:44
1

Use str_pad() where you set it to pad the left with 0's until the length of string is 2 chars.

echo str_pad($str - $int, 2, '0', STR_PAD_LEFT);
kittycat
  • 14,983
  • 9
  • 55
  • 80