• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1630
  • Last Modified:

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!
1 Solution
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.
How are you populating $info?  Are you sure the values are being copied correctly from $_POST?

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

Open in new window

satmanukAuthor Commented:
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......


You put me on the right trafck so you get the points.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now