Link to home
Start Free TrialLog in
Avatar of satmanuk
satmanukFlag for United Kingdom of Great Britain and Northern Ireland

asked on

convert number into string using php

Hi all.

I have a page where multiple records are shown. One of the pieces of data shown on each record is the time. This has been added to the database in 2 seperate fields timehr and timemin. the users add the time using 2 drop down list menus. the values of each hour and min do have the required 0 so i have 01,02,03, etc but when the data is added to the database 06 becomes 6, hence my question.

When i echo both timehr and timemin it works fine but when say its 6am in the databse the fields are filled with timehr = 6 and timemin = 0.

I want to add a zero to the left of timehr and to the right of timemin. so all times read 01:30, 06:00 etc and not 1:30, 6:0 etc

I have tried the following:
$s_Time = str_pad($info['timehr'], 2,'0', STR_PAD_LEFT) . ':' . str_pad($info['timemin'], 2, '0', STR_PAD_LEFT);

It doesnt work, instead i get 00:00 for every record regardless of what characters are in the data fields.

I am guessing it has somethiong to do with the numbers not being strings? Therefore it doesnt count any characters and thus gives 00.

Do i need to convert my $info['timehr'] into a string or am i complety barking up the wrong tree?


Can anyone help please?

Thanks in advance!
Avatar of pbeirne
pbeirne

If you are using mySQL you can set the timehr and timemin fields to type TINYINT, length 2 with an attribute of UNSIGNED ZEROFILL.  That way it will save all numbers with leading zeros.
ASKER CERTIFIED SOLUTION
Avatar of Rurne
Rurne
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

<?PHP
// 02:05
$info['timehr']=2;
$info['timemin']=5;
$fulltime = substr('00'.$info['timehr'],strlen-2).':'.substr('00'.$info['timemin'],strlen-2);
echo $fulltime.'<br>';
 
// 12:30
$info['timehr']=12;
$info['timemin']=30;
$fulltime = substr('00'.$info['timehr'],strlen-2).':'.substr('00'.$info['timemin'],strlen-2);
echo $fulltime.'<br>';
 
// 22:00
$info['timehr']=20;
$info['timemin']=0;
$fulltime = substr('00'.$info['timehr'],strlen-2).':'.substr('00'.$info['timemin'],strlen-2);
echo $fulltime.'<br>';
?>

Open in new window

Avatar of satmanuk

ASKER

I had the follwoing lines:

//Puts it into an array
  while($info = mysql_fetch_array( $data ))
 {

Like a silly man i am i had my str_pad lines of code above the above lines of code.

So the code hadnt dealt with $info{'blah'] yet.

That will teach me for coding through the night......

@Rurne

You put me on the right trafck so you get the points.