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)
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With