Saranya
Saranya

Reputation: 1151

How to get a whole number value from a variable in php?

The following is my code,

    $da =01;
    $cal_sunday = $da + 7;
    echo $cal_sunday;

the above calculation return the output as '8'.. i need the output as '08'...

Upvotes: 0

Views: 190

Answers (4)

Dominic Barnes
Dominic Barnes

Reputation: 28429

$da = 1;
$cal_sunday = $da + 7;
printf('%02s', $cal_sunday);

printf() and sprintf() work similarly, except the first does a direct output, while the later returns the value so it can be assigned to another variable.

$da = 1;
$cal_sunday = sprintf('%02s', $da + 7);
echo $cal_sunday;

Upvotes: 0

Jon Winstanley
Jon Winstanley

Reputation: 23311

Have a look at the sprintf function

Your calculation produces and integer but you require a string.

Use sprintf to return the string in the format you need.

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342373

you can use printf eg printf("%02d",$cal_sunday);

Upvotes: 1

Gumbo
Gumbo

Reputation: 655239

You can use sprintf to format your number:

echo sprintf('%02u', $cal_sunday);

Upvotes: 4

Related Questions