PHP date(): minutes without leading zeros - php

I'd like to know if there is a formatting letter for PHP's date() that allows me to print minutes without leading zeros, or whether I have to manually test for and remove leading zeros?

Use:
$minutes = intval(date('i'));

For times with more information than just minutes:
ltrim() - Strip whitespace (or other characters) from the beginning of a string
ltrim(date('i:s'), 0);
returns:
8:24

According to the PHP Documentation, the date() function does not have a placeholder for minutes without leading zeros.
You could, however, get that information by simply multiplying the dates, with a leading zero, by 1, turning it into an integer.
$minutesWithoutZero = 1* date( 'i' );

I tried to find this for seconds as well, gave up the search and just casting the result as a int like this:
echo (int)date("s");
That will get rid of the leading zero's in a fast efficient way.

Doesn't look like it, but you could do something like...
echo date('g:') . ltrim(date('i'), '0');
Alternately, you could cast the second call to date() with (int).

This also works
$timestamp = time(); // Or Your timestamp. Skip passing $timestamp if you want current time
echo (int)date('i',$timestamp);

I use this format if I need a XXmXXs format:
//Trim leading 0's and the 'm' if no minutes
ltrim(ltrim(gmdate("i\ms\s", $seconds), '0'), 'm');
This will output the following:
12m34s
1m23s
12s

i just did this one line solution
$min = intval(date('i',strtotime($date)));
Using ltrim method may remove all the leading zeroes.For ex if '00' min.In this case this will remove all the zeroes and gives you empty result.

My solution:
function seconds2string($seconds) {
if ($seconds == 0) {
return '-';
}
if ($seconds < 60) {
return date('0:s', $seconds);
}
if ($seconds < 3600) {
return ltrim(date('i:s', $seconds), 0);
}
return date('G:i:s', $seconds);
}
This will output:
0 seconds: -
10 seconds: 0:10
90 seconds: 1:30
301 seconds: 5:01
1804 seconds: 30:04
3601 seconds: 1:00:01

Just use this:
(int) date('i');

Or in mySQL just multiply it by 1, like such:
select f1, ..., date_format( fldTime , '%i' ) * 1 as myTime, ..., ...

$current_date = Date("n-j-Y");
echo $current_date;
// Result m-d-yy
9-10-2012

A quickie from me. Tell me what you think:
<?php function _wo_leading_zero($n) {
if(!isset($n[1])) return $n;
if(strpos($n, '.') !== false) {
$np = explode('.', $n); $nd = '.';
}
if(strpos($n, ',') !== false) {
if(isset($np)) return false;
$np = explode(',', $n); $nd = ',';
}
if(isset($np) && count($np) > 2) return false;
$n = isset($np) ? $np[0] : $n;
$nn = ltrim($n, '0');
if($nn == '') $nn = '0';
return $nn.(isset($nd) ? $nd : '').(isset($np[1]) ? $np[1] : '');
}
echo '0 => '._wo_leading_zero('0').'<br/>'; // returns 0
echo '00 => '._wo_leading_zero('00').'<br/>'; // returns 0
echo '05 => '._wo_leading_zero('05').'<br/>'; // returns 5
echo '0009 => '._wo_leading_zero('0009').'<br/>'; //returns 9
echo '01 => '._wo_leading_zero('01').'<br/>'; //returns 1
echo '0000005567 => '._wo_leading_zero('0000005567').'<br/>'; //returns 5567
echo '000.5345453 => '._wo_leading_zero('000.5345453').'<br/>'; //returns 0.5345453
echo '000.5345453.2434 => '._wo_leading_zero('000.5345453.2434').'<br/>'; //returns false
echo '000.534,2434 => '._wo_leading_zero('000.534,2434').'<br/>'; //returns false
echo date('m').' => '._wo_leading_zero(date('m')).'<br/>';
echo date('s').' => '._wo_leading_zero(date('s')).'<br/>'; ?>

use PHP's absolute value function:
abs( '09' ); // result = 9
abs( date( 'i' ) ); // result = minutes without leading zero

My Suggestion is Read this beautiful documentation it have all details of php date functions
Link of Documentation
And as per your question you can use i - Minutes with leading zeros (00 to 59) Which return you minutes with leading zero(0).
And Also introducing [Intval()][2] function returns the integer value of a variable. You can not use the intval() function on an object

Related

How to subtract time from time array using php?

Hello seniors I have a question related to some PHP script.
I have an array containing time => ['12:10', '4:16', '2:5'] and have one html form containing input field of type 'number'.
I want when I enter some value in my form input field for example I enter 7, so after submitting the form in back-end the number 7 which i enter in input field is subtracted from the array which I mentioned above and I will get the result array like:
['5:10', '4:16', '2:5']
I have tried something like that but not able to implement my logic
$val = array(1, 0, 2, 1, 1);
$subtract = 3.5;
foreach ($val as $key => $item) {
if ($subtract >= $item) {
$subtract -= $item;
$val[$key] = 0;
} else {
$val[$key] -= $subtract;
$subtract = 0;
}
}
Any kind of help is highly appreciated
You can use Carbon library for date/time manipulation:
<?php
use Carbon\Carbon;
$times = ['17:46', '03:05', '21:56'];
$timeshift = 3;
$new_times = array_map(
fn($t) => Carbon::createFromFormat('H:i', $t)
->subHours($timeshift)
->format('H:i'),
$times
);
Test Carbon library online
No need for library, just convert your first array to seconds: 1 hour = 3600 ; 1 minute = 60 ; 12:10 is 12 x 3600 + 10 x 60, then you do the same thing to your $_POST value, then use gmdate() to retrieve the original format of your array
$myTimes=array('12:10', '4:16', '2:5');
//do the math
$splittedTime = explode(":", $myTimes[0]); //in your case
$timeInSeconds = $splittedTime[0] * 3600 + $splittedTime[1] * 60 ;
//do the same thing to your your $_POST value if needed or simply
$totalReduceby = 7 * 3600;
// get new total of seconds
$newTime= $timeInSeconds - $totalReduceby;
$result = ltrim(gmdate("H:i", $newTime),0); //ltrim to remove the leading 0
$myTimes=array($result, '4:16', '2:5');
//print_r($myTimes);
time => ['12:10', '4:16', '2:5']
[...]
the number 7 which i enter in input field is subtracted from the array
I will get the result array like: ['5:10', '4:16', '2:5']
Your example is a little ambiguous. Do you only want to subtract the field value from the first element of the array, always? Or only from those elements which are greater than the submitted value?
It's pretty straightforward to subtract minutes from a mm:ss time string; simplest is probably to generalize so that the amount to subtract is also allowed to be mm:ss instead of always being a whole number of minutes. I would just explode both of them, turn them into total seconds (minutes*60+seconds), subtract those, and then turn back into mm:ss. Both conversions might be worth their own functions:
function mmssToSeconds($timeStr) {
if (str_contains($timeStr, ':')) {
list($min, $sec) = explode(':', $timeStr);
} else {
list($min, $sec) = array($timeStr, 0);
}
if ($min < 0) {
return 60*$min - $sec;
} else {
return 60*$min + $sec;
}
}
function secondsToMmss($seconds) {
$abs = abs($seconds);
$sgn = $seconds / $abs;
$min = floor($abs / 60);
$sec = $abs % 60;
return ($sgn < 0 ? '-' : '').sprintf('%d:%02d', $min, $sec);
}
And then the subtraction is easy:
function subtractMinutes($from, $delta) {
return secondsToMmss(mmssToSeconds($from) - mmssToSeconds($delta));
}
If you want to subtract from each element that is big enough, you could use a loop like this:
foreach ($ary['time'] as $i => $t) {
if ((int)$t > $subtract) {
$ary['time'][$i] = subtractMinutes($t, $subtract);
}
}
The comparison works because the cast from string to int ignores everything after the first non-digit, so '12:10' just becomes 12, which is > 7.

Ranking with Echo on Php [duplicate]

I want to display numbers as follows
1 as 1st,
2 as 2nd,
...,
150 as 150th.
How should I find the correct ordinal suffix (st, nd, rd or th) for each number in my code?
from wikipedia:
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if (($number %100) >= 11 && ($number%100) <= 13)
$abbreviation = $number. 'th';
else
$abbreviation = $number. $ends[$number % 10];
Where $number is the number you want to write. Works with any natural number.
As a function:
function ordinal($number) {
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if ((($number % 100) >= 11) && (($number%100) <= 13))
return $number. 'th';
else
return $number. $ends[$number % 10];
}
//Example Usage
echo ordinal(100);
PHP has built-in functionality for this. It even handles internationalization!
$locale = 'en_US';
$nf = new NumberFormatter($locale, NumberFormatter::ORDINAL);
echo $nf->format($number);
Note that this functionality is only available in PHP 5.3.0 and later.
This can be accomplished in a single line by leveraging similar functionality in PHP's built-in date/time functions. I humbly submit:
Solution:
function ordinalSuffix( $n )
{
return date('S',mktime(1,1,1,1,( (($n>=10)+($n>=20)+($n==0))*10 + $n%10) ));
}
Detailed Explanation:
The built-in date() function has suffix logic for handling nth-day-of-the-month calculations. The suffix is returned when S is given in the format string:
date( 'S' , ? );
Since date() requires a timestamp (for ? above), we'll pass our integer $n as the day parameter to mktime() and use dummy values of 1 for the hour, minute, second, and month:
date( 'S' , mktime( 1 , 1 , 1 , 1 , $n ) );
This actually fails gracefully on values out of range for a day of the month (i.e. $n > 31) but we can add some simple inline logic to cap $n at 29:
date( 'S', mktime( 1, 1, 1, 1, ( (($n>=10)+($n>=20))*10 + $n%10) ));
The only positive value(May 2017) this fails on is $n == 0, but that's easily fixed by adding 10 in that special case:
date( 'S', mktime( 1, 1, 1, 1, ( (($n>=10)+($n>=20)+($n==0))*10 + $n%10) ));
Update, May 2017
As observed by #donatJ, the above fails above 100 (e.g. "111st"), since the >=20 checks are always returning true. To reset these every century, we add a filter to the comparison:
date( 'S', mktime( 1, 1, 1, 1, ( (($n>=10)+($n%100>=20)+($n==0))*10 + $n%10) ));
Just wrap it in a function for convenience and off you go!
Here is a one-liner:
$a = <yournumber>;
echo $a.substr(date('jS', mktime(0,0,0,1,($a%10==0?9:($a%100>20?$a%10:$a%100)),2000)),-2);
Probably the shortest solution. Can of course be wrapped by a function:
function ordinal($a) {
// return English ordinal number
return $a.substr(date('jS', mktime(0,0,0,1,($a%10==0?9:($a%100>20?$a%10:$a%100)),2000)),-2);
}
Regards,
Paul
EDIT1: Correction of code for 11 through 13.
EDIT2: Correction of code for 111, 211, ...
EDIT3: Now it works correctly also for multiples of 10.
from http://www.phpro.org/examples/Ordinal-Suffix.html
<?php
/**
*
* #return number with ordinal suffix
*
* #param int $number
*
* #param int $ss Turn super script on/off
*
* #return string
*
*/
function ordinalSuffix($number, $ss=0)
{
/*** check for 11, 12, 13 ***/
if ($number % 100 > 10 && $number %100 < 14)
{
$os = 'th';
}
/*** check if number is zero ***/
elseif($number == 0)
{
$os = '';
}
else
{
/*** get the last digit ***/
$last = substr($number, -1, 1);
switch($last)
{
case "1":
$os = 'st';
break;
case "2":
$os = 'nd';
break;
case "3":
$os = 'rd';
break;
default:
$os = 'th';
}
}
/*** add super script ***/
$os = $ss==0 ? $os : '<sup>'.$os.'</sup>';
/*** return ***/
return $number.$os;
}
?>
Simple and Easy Answer will be:
$Day = 3;
echo date("S", mktime(0, 0, 0, 0, $Day, 0));
//OUTPUT - rd
I wrote this for PHP4.
It's been working ok & it's pretty economical.
function getOrdinalSuffix($number) {
$number = abs($number) % 100;
$lastChar = substr($number, -1, 1);
switch ($lastChar) {
case '1' : return ($number == '11') ? 'th' : 'st';
case '2' : return ($number == '12') ? 'th' : 'nd';
case '3' : return ($number == '13') ? 'th' : 'rd';
}
return 'th';
}
you just need to apply given function.
function addOrdinalNumberSuffix($num) {
if (!in_array(($num % 100),array(11,12,13))){
switch ($num % 10) {
// Handle 1st, 2nd, 3rd
case 1: return $num.'st';
case 2: return $num.'nd';
case 3: return $num.'rd';
}
}
return $num.'th';
}
Generically, you can use that and call echo get_placing_string(100);
<?php
function get_placing_string($placing){
$i=intval($placing%10);
$place=substr($placing,-2); //For 11,12,13 places
if($i==1 && $place!='11'){
return $placing.'st';
}
else if($i==2 && $place!='12'){
return $placing.'nd';
}
else if($i==3 && $place!='13'){
return $placing.'rd';
}
return $placing.'th';
}
?>
I made a function that does not rely on the PHP's date(); function as it's not necessary, but also made it as compact and as short as I think is currently possible.
The code: (121 bytes total)
function ordinal($i) { // PHP 5.2 and later
return($i.(($j=abs($i)%100)>10&&$j<14?'th':(($j%=10)>0&&$j<4?['st', 'nd', 'rd'][$j-1]:'th')));
}
More compact code below.
It works as follows:
printf("The %s hour.\n", ordinal(0)); // The 0th hour.
printf("The %s ossicle.\n", ordinal(1)); // The 1st ossicle.
printf("The %s cat.\n", ordinal(12)); // The 12th cat.
printf("The %s item.\n", ordinal(-23)); // The -23rd item.
Stuff to know about this function:
It deals with negative integers the same as positive integers and keeps the sign.
It returns 11th, 12th, 13th, 811th, 812th, 813th, etc. for the -teen numbers as expected.
It does not check decimals, but will leave them in place (use floor($i), round($i), or ceil($i) at the beginning of the final return statement).
You could also add format_number($i) at the beginning of the final return statement to get a comma-separated integer (if you're displaying thousands, millions, etc.).
You could just remove the $i from the beginning of the return statement if you only want to return the ordinal suffix without what you input.
This function works commencing PHP 5.2 released November 2006 purely because of the short array syntax. If you have a version before this, then please upgrade because you're nearly a decade out of date! Failing that, just replace the in-line ['st', 'nd', 'rd'] with a temporary variable containing array('st', 'nd', 'rd');.
The same function (without returning the input), but an exploded view of my short function for better understanding:
function ordinal($i) {
$j = abs($i); // make negatives into positives
$j = $j%100; // modulo 100; deal only with ones and tens; 0 through 99
if($j>10 && $j<14) // if $j is over 10, but below 14 (so we deal with 11 to 13)
return('th'); // always return 'th' for 11th, 13th, 62912th, etc.
$j = $j%10; // modulo 10; deal only with ones; 0 through 9
if($j==1) // 1st, 21st, 31st, 971st
return('st');
if($j==2) // 2nd, 22nd, 32nd, 582nd
return('nd'); //
if($j==3) // 3rd, 23rd, 33rd, 253rd
return('rd');
return('th'); // everything else will suffixed with 'th' including 0th
}
Code Update:
Here's a modified version that is 14 whole bytes shorter (107 bytes total):
function ordinal($i) {
return $i.(($j=abs($i)%100)>10&&$j<14?'th':#['th','st','nd','rd'][$j%10]?:'th');
}
Or for as short as possible being 25 bytes shorter (96 bytes total):
function o($i){return $i.(($j=abs($i)%100)>10&&$j<14?'th':#['th','st','nd','rd'][$j%10]?:'th');}
With this last function, simply call o(121); and it'll do exactly the same as the other functions I listed.
Code Update #2:
Ben and I worked together and cut it down by 38 bytes (83 bytes total):
function o($i){return$i.#(($j=abs($i)%100)>10&&$j<14?th:[th,st,nd,rd][$j%10]?:th);}
We don't think it can possibly get any shorter than this! Willing to be proven wrong, however. :)
Hope you all enjoy.
An even shorter version for dates in the month (up to 31) instead of using mktime() and not requiring pecl intl:
function ordinal($n) {
return (new DateTime('Jan '.$n))->format('jS');
}
or procedurally:
echo date_format(date_create('Jan '.$n), 'jS');
This works of course because the default month I picked (January) has 31 days.
Interestingly enough if you try it with February (or another month without 31 days), it restarts before the end:
...clip...
31st
1st
2nd
3rd
so you could count up to this month's days with the date specifier t in your loop: number of days in the month.
function ordinal($number){
$last=substr($number,-1);
if( $last>3 || $last==0 || ( $number >= 11 && $number <= 19 ) ){
$ext='th';
}else if( $last==3 ){
$ext='rd';
}else if( $last==2 ){
$ext='nd';
}else{
$ext='st';
}
return $number.$ext;
}
Here is the correct solution
$numberFormatter = new NumberFormatter('en_US', NumberFormatter::ORDINAL);
echo $numberFormatter->format(11);
Found an answer in PHP.net
<?php
function ordinal($num)
{
// Special case "teenth"
if ( ($num / 10) % 10 != 1 )
{
// Handle 1st, 2nd, 3rd
switch( $num % 10 )
{
case 1: return $num . 'st';
case 2: return $num . 'nd';
case 3: return $num . 'rd';
}
}
// Everything else is "nth"
return $num . 'th';
}
?>
Here's another very short version using the date functions. It works for any number (not constrained by days of the month) and takes into account that *11th *12th *13th does not follow the *1st *2nd *3rd format.
function getOrdinal($n)
{
return $n . date_format(date_create('Jan ' . ($n % 100 < 20 ? $n % 20 : $n % 10)), 'S');
}
I realise this is an ancient post, however it's probably worth adding that as of PHP 8, the match control structure allows a more concise:
$ordinal = match(in_array(abs($position)%100, [11, 12, 13]) ? 0 : abs($position)%10) { 1 => 'st', 2 => 'nd', 3 => 'rd', default => 'th' };
If you need to append that to the position to get a place:
$place = $position.match(in_array(abs($position)%100, [11, 12, 13]) ? 0 : abs($position)%10) { 1 => 'st', 2 => 'nd', 3 => 'rd', default => 'th' };
You can obviously simplify that out if you know your position will always be positive or less than 11 or whatever.
I fond this small snippet
<?php
function addOrdinalNumberSuffix($num) {
if (!in_array(($num % 100),array(11,12,13))){
switch ($num % 10) {
// Handle 1st, 2nd, 3rd
case 1: return $num.'st';
case 2: return $num.'nd';
case 3: return $num.'rd';
}
}
return $num.'th';
}
?>
HERE

Convert a string to seconds with PHP

I have string '6m15s' in PHP that I would like to convert in to time or ideally seconds. I am using the strtotime() function like:
$time = date('H:i:s', strtotime('6m15s'));
echo $time;
But all I get '01:00:00'. Is this possible to convert my string and if so what would be the best way to do so?
You could use substr():
$string = '6m15s';
$minute = substr($string, 0, 1);
$second = substr($string, 2, 2);
echo date('H:i:s', strtotime("00:$minute:$second"));
// outputs 00:06:15
If you're trying to get the total number of seconds then something like:
preg_match('/((?<h>[\d]+)h)?((?<m>[\d]+)m)?((?<s>[\d]+)s?)/', $var, $m);
echo ($m['h']* 60 + $m['m']) * 60 + $m['s']; // 375
This looks for hours as well, as in 1h6m15s.
If you are working with the fix patterns then you can construct a method like:
function stringToSecondByPattern($subject, $pattern = '/(\d+)m(\d+)s/') {
$matches = [];
preg_match($pattern, $subject, $matches);
list($original, $minuets, $seconds) = $matches;
$secondsSum = $seconds + ($minuets * 60);
return $secondsSum;
}
print stringToSecondByPattern('6m15s');

PHP - For Loop Keep Significant Digits [duplicate]

This question already has answers here:
Zero-pad digits in string
(5 answers)
Closed 2 years ago.
I have a variable which contains the value 1234567.
I would like it to contain exactly 8 digits, i.e. 01234567.
Is there a PHP function for that?
Use sprintf :
sprintf('%08d', 1234567);
Alternatively you can also use str_pad:
str_pad($value, 8, '0', STR_PAD_LEFT);
Given that the value is in $value:
To echo it:
printf("%08d", $value);
To get it:
$formatted_value = sprintf("%08d", $value);
That should do the trick
When I need 01 instead of 1, the following worked for me:
$number = 1;
$number = str_pad($number, 2, '0', STR_PAD_LEFT);
echo str_pad("1234567", 8, '0', STR_PAD_LEFT);
sprintf is what you need.
EDIT (somehow requested by the downvotes), from the page linked above, here's a sample "zero-padded integers":
<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>
Though I'm not really sure what you want to do you are probably looking for sprintf.
This would be:
$value = sprintf( '%08d', 1234567 );
Simple answer
$p = 1234567;
$p = sprintf("%08d",$p);
I'm not sure how to interpret the comment saying "It will never be more than 8 digits" and if it's referring to the input or the output. If it refers to the output you would have to have an additional substr() call to clip the string.
To clip the first 8 digits
$p = substr(sprintf('%08d', $p),0,8);
To clip the last 8 digits
$p = substr(sprintf('%08d', $p),-8,8);
If the input numbers have always 7 or 8 digits, you can also use
$str = ($input < 10000000) ? 0 . $input : $input;
I ran some tests and get that this would be up to double as fast as str_pad or sprintf.
If the input can have any length, then you could also use
$str = substr('00000000' . $input, -8);
This is not as fast as the other one, but should also be a little bit faster than str_pad and sprintf.
Btw: My test also said that sprintf is a little faster than str_pad. I made all tests with PHP 5.6.
Edit: Altough the substr version seems to be still very fast (PHP 7.2), it also is broken in case your input can be longer than the length you want to pad to. E.g. you want to pad to 3 digits and your input has 4 than substr('0000' . '1234', -3) = '234' will only result in the last 3 digits
$no_of_digit = 10;
$number = 123;
$length = strlen((string)$number);
for($i = $length;$i<$no_of_digit;$i++)
{
$number = '0'.$number;
}
echo $number; /////// result 0000000123
I wrote this simple function to produce this format: 01:00:03
Seconds are always shown (even if zero).
Minutes are shown if greater than zero or if hours or days are required.
Hours are shown if greater than zero or if days are required.
Days are shown if greater than zero.
function formatSeconds($secs) {
$result = '';
$seconds = intval($secs) % 60;
$minutes = (intval($secs) / 60) % 60;
$hours = (intval($secs) / 3600) % 24;
$days = intval(intval($secs) / (3600*24));
if ($days > 0) {
$result = str_pad($days, 2, '0', STR_PAD_LEFT) . ':';
}
if(($hours > 0) || ($result!="")) {
$result .= str_pad($hours, 2, '0', STR_PAD_LEFT) . ':';
}
if (($minutes > 0) || ($result!="")) {
$result .= str_pad($minutes, 2, '0', STR_PAD_LEFT) . ':';
}
//seconds aways shown
$result .= str_pad($seconds, 2, '0', STR_PAD_LEFT);
return $result;
} //funct
Examples:
echo formatSeconds(15); //15
echo formatSeconds(100); //01:40
echo formatSeconds(10800); //03:00:00 (mins shown even if zero)
echo formatSeconds(10000000); //115:17:46:40
You can always abuse type juggling:
function zpad(int $value, int $pad): string {
return substr(1, $value + 10 ** $pad);
}
This wont work as expected if either 10 ** pad > INT_MAX or value >= 10 * pad.

Formatting a number with leading zeros in PHP [duplicate]

This question already has answers here:
Zero-pad digits in string
(5 answers)
Closed 2 years ago.
I have a variable which contains the value 1234567.
I would like it to contain exactly 8 digits, i.e. 01234567.
Is there a PHP function for that?
Use sprintf :
sprintf('%08d', 1234567);
Alternatively you can also use str_pad:
str_pad($value, 8, '0', STR_PAD_LEFT);
Given that the value is in $value:
To echo it:
printf("%08d", $value);
To get it:
$formatted_value = sprintf("%08d", $value);
That should do the trick
When I need 01 instead of 1, the following worked for me:
$number = 1;
$number = str_pad($number, 2, '0', STR_PAD_LEFT);
echo str_pad("1234567", 8, '0', STR_PAD_LEFT);
sprintf is what you need.
EDIT (somehow requested by the downvotes), from the page linked above, here's a sample "zero-padded integers":
<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>
Though I'm not really sure what you want to do you are probably looking for sprintf.
This would be:
$value = sprintf( '%08d', 1234567 );
Simple answer
$p = 1234567;
$p = sprintf("%08d",$p);
I'm not sure how to interpret the comment saying "It will never be more than 8 digits" and if it's referring to the input or the output. If it refers to the output you would have to have an additional substr() call to clip the string.
To clip the first 8 digits
$p = substr(sprintf('%08d', $p),0,8);
To clip the last 8 digits
$p = substr(sprintf('%08d', $p),-8,8);
If the input numbers have always 7 or 8 digits, you can also use
$str = ($input < 10000000) ? 0 . $input : $input;
I ran some tests and get that this would be up to double as fast as str_pad or sprintf.
If the input can have any length, then you could also use
$str = substr('00000000' . $input, -8);
This is not as fast as the other one, but should also be a little bit faster than str_pad and sprintf.
Btw: My test also said that sprintf is a little faster than str_pad. I made all tests with PHP 5.6.
Edit: Altough the substr version seems to be still very fast (PHP 7.2), it also is broken in case your input can be longer than the length you want to pad to. E.g. you want to pad to 3 digits and your input has 4 than substr('0000' . '1234', -3) = '234' will only result in the last 3 digits
$no_of_digit = 10;
$number = 123;
$length = strlen((string)$number);
for($i = $length;$i<$no_of_digit;$i++)
{
$number = '0'.$number;
}
echo $number; /////// result 0000000123
I wrote this simple function to produce this format: 01:00:03
Seconds are always shown (even if zero).
Minutes are shown if greater than zero or if hours or days are required.
Hours are shown if greater than zero or if days are required.
Days are shown if greater than zero.
function formatSeconds($secs) {
$result = '';
$seconds = intval($secs) % 60;
$minutes = (intval($secs) / 60) % 60;
$hours = (intval($secs) / 3600) % 24;
$days = intval(intval($secs) / (3600*24));
if ($days > 0) {
$result = str_pad($days, 2, '0', STR_PAD_LEFT) . ':';
}
if(($hours > 0) || ($result!="")) {
$result .= str_pad($hours, 2, '0', STR_PAD_LEFT) . ':';
}
if (($minutes > 0) || ($result!="")) {
$result .= str_pad($minutes, 2, '0', STR_PAD_LEFT) . ':';
}
//seconds aways shown
$result .= str_pad($seconds, 2, '0', STR_PAD_LEFT);
return $result;
} //funct
Examples:
echo formatSeconds(15); //15
echo formatSeconds(100); //01:40
echo formatSeconds(10800); //03:00:00 (mins shown even if zero)
echo formatSeconds(10000000); //115:17:46:40
You can always abuse type juggling:
function zpad(int $value, int $pad): string {
return substr(1, $value + 10 ** $pad);
}
This wont work as expected if either 10 ** pad > INT_MAX or value >= 10 * pad.

Categories