'02 (str) - 1 (int) = 01 (str) How to get result like this? [duplicate]

<?php

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

$result = $str-$int;

echo $result // 1

?>

But I need result = 01

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



Solution 1:[1]

<?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

Solution 2:[2]

try

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

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

Solution 3:[3]

<?

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

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

?>

Solution 4:[4]

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);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 fvu
Solution 3 skurton
Solution 4 cryptic ?