I want to customize my $number variable so that it will return like this 00:00:00
I want to insert ":" after every 2 numbers
Example:
$num = 120834;
So i want the output like this : 12:08:34
CodePudding user response:
If you have always 8 digits, try this:
$num = '120466';
$new = substr($num, 0, 2) .':'. substr($num, 2, 2).':'. substr($num, 4, 2);
Or use implode();
$new = implode(":", str_split(strval($num), 2));
Credit is to @user19513069
CodePudding user response:
I think this is the most readable way:
You can use str_split() to separate it in an array based on the number of digits you want, 2 in this case.
$num = 120834;
$numParts = str_split($num, 2);
// then you can simply add it to a string
echo "$numParts[0]:$numParts[1]:$numParts[2]"; //12:08:34
Heres a function to do it easily for you:
//Then you can simply pass in the number you want to convert
function numberToTime($num)
{
$numParts = str_split($num, 2);
return "$numParts[0]:$numParts[1]:$numParts[2]";
}
CodePudding user response:
You can also use chunk_split for this:
substr(chunk_split("120834", 2, ":"), 0, -1)