Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formating numbers with leading zeros in Blade view

I have the following code in a Blade view:

@for ($i = 1; $i <= 99; $i++)
    <div id="player-{{ $i }}">{{ $i }}</div>
@endfor

Which generates divs with ids player-1, player-2, player-3, etc. But what I really need is to have the ids player-01, player-02, player-03, etc. Is there a function in blade to do that like printf in PHP? or using a ternary operator is the best way around?

(The ternary operator works fine when only one zero needs to be added, but doesn't work that fine when more zeros are needed)

like image 304
AngelGris Avatar asked Apr 01 '17 19:04

AngelGris


People also ask

How do I add a zero in front of a single digit in Python?

Use the str. zfill() method to add leading zeros to the string. The method takes the width of the string and pads it with leading zeros.


1 Answers

You can use str_pad($yourNumebr,$lengthOfYourNumber,$padString,$padType) to do this.

For more details click here

@for ($i = 1; $i <= 99; $i++)
    <div id="player-{{ str_pad($i,2,'0',STR_PAD_LEFT) }}">{{ $i }}</div>
@endfor

Or

sprintf('%02d', $i);
like image 109
Rana Avatar answered Oct 13 '22 01:10

Rana