user1097772
user1097772

Reputation: 3539

Formated print opening hours (string) in php

In C there is formatted print, which allows formatted printing of numbers - aligning them. Is something similar possible in PHP with strings?

I have 2 strings $open_time, $close_time. For example $open_time="12:00", $close_time="23:00".

desired output

12:00 - 23:00
 7:00 - 20:00
12:30 -  1:00
 5:00 -  6:00

output with echo

12:00 - 23:00
7:00 - 20:00
12:30 - 1:00
5:00 - 6:00

See that 12:00 are 5 characters, 7:00 are 4 characters? I need to add a space. Is there a function in PHP which will print it with mask like in C (not sure if this is even possible in C)

some_print("string_5_charactersSPACE-SPACEstring_5_characters", $open_time,$close_time);

where SPACE mean space: "%string_5_characters - %string_5_characters".

My simple solution is check if the string has 5 chars and if not I will just concatenate it with a space to get 5 chars ... But I'm curious if its possible to do it just by one function like it was possible with printing numbers in C.

Upvotes: 1

Views: 111

Answers (1)

vascowhite
vascowhite

Reputation: 18440

You are looking for sprintf(), take a look at printf() too.

Upvotes: 2

Related Questions