PHP - Formatting Floats
I've been wracking my brain trying to figure this simple problem out and I can't for the life of me figure out the best way to do it.
I have the following array: $n = array('81.0', '80.5', '70.5', '67.0', '65.5'); I only want to display the numbers to one decimal place if it's not a whole number, like so. 81 80.5 70.5 67 65.5 I've tried looking for a solution with sprintf(), rtrim() and number_format(), but what's the best way to do it? Regards Rich Similar TutorialsHi, I am trying to print my database records into a php page. I am able to succesfully print the values however the values are being duplicated. For example If I have two records in the employee_details, every these two records are being printed twice on my php page. can anyone tell me the reason why? The output that I see is as follows 7 7 3a7cf5162a9c0a5014c92021e7ca0bf0 3a7cf5162a9c0a5014c92021e7ca0bf0 Bryan Bryan 4111 4111 Admin Admin 6 6 6743c3d1519ab4f2cd9a78ab09a511bd 6743c3d1519ab4f2cd9a78ab09a511bd Raul Raul 601 W Yandell Dr, 601 W Yandell Dr, Admin Admin <html> <head> </head> <body> <?php mysql_connect("localhost","root",""); mysql_select_db("encryption") or die(mysql_error()); $query = mysql_query("select * from employee_details"); ?> <table> <?php for($counter = 0;$row=mysql_fetch_array($query); $counter++) { print ("<tr>"); foreach($row as $key=> $value) print ("<td>$value</td>"); print ("</tr>"); } ?> </table> </body> </html> Hi Simple question, how do I reFormat a date. $dateCreated (2012-01-14) to become: 14th jan 2012 So far I have this, but it's not working: Code: [Select] $expDate = explode('-',$dateCreated); $date1 = mktime(0, 0, 0, date('m', $expDate[1]), date('d', $expDate[2]), date('Y', $expDate[0])); $date = date('d m Y', $date1); Thanks Hi there, I need a PHP number format to match one and all of these sequence of numbers: 8500.00 9999.99 15.00 0.00 Hi everyone, I am having some odd issues with sending php generated emails. Essentially, what I'd like to know is how can I ensure they go into the inbox, and not get shunted to the junk mail folder. I assume this is s formatting issue, and it only happens sometimes. I am creating html emails. I have included my headers below: $headers = "From: <Real Money Help>\r\n"; $headers .= 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n"; Any help would be appreciated. Thanks. I'm presently formatting surnames like this: Code: [Select] $surname = ucfirst(strtolower($surname))) .. so that SMITH, and smith ... both look like: Smith. That's all fine, but how do I ensure that... O'BRIEN o'brien o' brien ... all look like O'Brien ? That is, where no spaces are allowed to appear in the surname and where the first letter, as well as the one following the apostrophe are both capitalised. TIA Hi all, I have features on my website which require a time limit untill they can do the thing agian, but at the current mintue ive got the time in seconds. How can I make a function which will give the time in minutes instaid of seconds. Example: If it was a 2 mintue waiting time instaid of being 120 Seconds it will be 2min(s) 0sec(s). Example of my Current Code: $timewaiting = time() + 160; // Waiting time. (2min) if ($user->lasttime > time()){ $howlongleft = $user->lasttime - time(); echo ("You must wait $howlongleft"); Thanks for any help given. I am having a problem with what is probably encoding. I am pulling strings from a WordPress database. Below is a sample string: Code: [Select] Sed nec neque quis sapien scelerisque aliquet. In in est odio, ac auctor erat. Vestibulum fringilla dapibus sodales. Morbi facilisis egestas arcu, eu semper mi luctus vitae. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse sollicitudin, metus sed hendrerit tristique, enim ante venenatis metus, ac consectetur mauris lorem et felis. Phasellus ac purus massa. Aliquam ligula mauris, iaculis et posuere vitae, pellentesque sit amet leo. Praesent at eros et lacus scelerisque feugiat. Aliquam non facilisis libero. Ut blandit leo ut tortor convallis porttitor. Aliquam erat volutpat. Aliquam rhoncus rutrum metus, tempor sollicitudin ante laoreet in. Sed tincidunt nibh a augue euismod sagittis. Fusce ullamcorper ultricies nisi, sit amet elementum mi scelerisque eget. Cras sed elit ligula, sit amet aliquam lectus. Nulla vel mollis nibh. Pellentesque ultricies, dui non aliquam eleifend, tortor ligula blandit dolor, quis interdum diam augue non eros. Nullam id molestie nunc. Integer id tempus est. When WordPress displays this text, it is formatted correctly, with spaces between paragraphs, etc. When I pull the string from the database, and echo it onto a page, the spaces between paragraphs are replaced by spaces, so in the end the output is as follows: Code: [Select] Sed nec neque quis sapien scelerisque aliquet. In in est odio, ac auctor erat. Vestibulum fringilla dapibus sodales. Morbi facilisis egestas arcu, eu semper mi luctus vitae. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse sollicitudin, metus sed hendrerit tristique, enim ante venenatis metus, ac consectetur mauris lorem et felis. Phasellus ac purus massa. Aliquam ligula mauris, iaculis et posuere vitae, pellentesque sit amet leo. Praesent at eros et lacus scelerisque feugiat. Aliquam non facilisis libero. Ut blandit leo ut tortor convallis porttitor. Aliquam erat volutpat. Aliquam rhoncus rutrum metus, tempor sollicitudin ante laoreet in. Sed tincidunt nibh a augue euismod sagittis. Fusce ullamcorper ultricies nisi, sit amet elementum mi scelerisque eget. Cras sed elit ligula, sit amet aliquam lectus. Nulla vel mollis nibh. Pellentesque ultricies, dui non aliquam eleifend, tortor ligula blandit dolor, quis interdum diam augue non eros. Nullam id molestie nunc. Integer id tempus est. What can I do to follow WordPress' formatting? Hi there, So I have data which I am fetching from two tables link in a one-to-many relationship using the following code: sql = "select authcourses.id as id, title, date_format(closingdate, '%d.%m.%y') as date, name from authcourses inner join authorities on authorityid = authorities.id order by authorityid"; $result = mysqli_query($link, $sql); if(!$result) { $error = 'Unable to get list of authorities'; include '../../error.html.php'; exit(); } while ($row = mysqli_fetch_array($result)) { $authcourses[] = array('name' => $row['name'], 'title' => $row ['title'], 'date' => $row['date'], 'id' => $row['id']); } I then output the data in a table like this: Code: [Select] <table> <thead><th>Title</th><th>Closing Date</th><th>Action</th></thead> <tbody> <?php foreach ($authcourses as $authcourse): ?> <tr> <form action="?" method="post"> <tr> <td><?php htmlout($authcourse['name']); ?></td> <!-- custom function htmlout($text) see helpers.inc.php --> <td><?php htmlout($authcourse['title']); ?></td> <td><?php htmlout($authcourse['date']); ?></td> <td> <input type="hidden" name="id" value="<?php echo $authcourse['id']; ?>" /> <input type="submit" name="action" value="Edit" /> <input type="submit" name="action" value="Delete" /> </td> </tr> </form> <?php endforeach; ?> </tbody> </table> The htmlout() is a custom function which is basically "echo htmlspecialchars($str)", and you can ignore the form stuff. I get an out put like this: York, Course 1, 2011-02-15 York, Course 2, 2011-03-01 Manchester, Course 3, 2011-06-17 Manchester, Course 4, 2011-08-12 Derby, Course 5, 2011-01-10 Barnet, Course 6, 2011-08-19 Barnet, Course 7, 2011-06-23 etc etc... What I want is something like this: York: Course 1, date Course 2, date Manchester: Course 3, date Course 4, date Derby: Course 5, date Barnet: Course 6, date Course 7, date etc.. I guess I'd like to load an array for each of the authorities (cities) with the course info, then I can output it in my form like this: Code: [Select] <?php foreach ($authcourses as $authcourse): ?> <h1><?php htmlout($authcourse['name'] ?>: </h1> <?php foreach ($courses as $course): ?> <p><?php htmlout($course['title'];?><p> <p><?php htmlout($course['date'];?></p> <?php endforeach; ?> <?php endforeach; ?> I hope that makes sense... Any help would be great. Cheers, Mike Hi everyone, this is quite a big one, and I am new to programming. In the code below you will see I have created a 'Lucky Lotto Dip'. The display function allows the user to choose how many draws they want then by way of the shuffle() 6 numbers are generated randomly for each line. I have two questions. (1) I have managed by way of an if statement to automatically check the first number in the array $draw, how do I get it to check for 2 match's, 3 match's and so on up to 6 match's. And secondly if the first number is matched I have managed to get it to repeat itself and if to show a match, but how do I get it to repeat itself on the line below the selected numbers? I know this is difficult but if anyone can help I will be very grateful! Code: [Select] <?php class Game { public $draw = array(10,25,36,3,12,13); public $numbers = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30, 31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49); public $age; public $count; function __construct($sub1, $sub2) { $this->name = $sub1; $this->age = $sub2; return $this->name;age; } function checkAge() { if ($this->age <18) { return "Sorry $this->name, you are too young to gamble"; } else { return "Hi $this->name welcome to Lucky Lotto Dip, how many draws would you like?"; } } function display($sub3) { shuffle ($this->numbers); $this->count = $sub3; echo "<pre>"; echo "*********************"; echo "<br />"; echo "* Lucky Lotto *"; echo "<br />"; echo "*********************"; while ($this->count >0) { echo "<br />"; echo "* "; for ($j =0; $j <6; $j++) // For loop if ($this->numbers[$j] <10) { echo " " . $this->numbers[$j] . " "; if ($this->numbers[$j] == $this->draw[0]) { echo $this->numbers[$j] = $this->draw[0]; } } else { echo $this->numbers[$j] . " "; if ($this->numbers[$j] == $this->draw[0]) { echo $this->numbers[$j] = $this->draw[0]; } } echo "* "; echo "<br />"; echo "*********************"; echo "<br />"; echo " "; echo "<br />"; echo "*********************"; $this->count --; shuffle ($this->numbers); } } } $object2 = new Game("Chris", 36); echo $object2->checkAge(); echo $object2->display(4); ?> Hi, Has anyone come across an issue when saving DOM to a file and Code: [Select] $document->preserveWhiteSpace = false; $document->formatOutout = true; has no effect? Having used unix timestamps in the past formatting the date used to be easy. But since converting to mysql DATETIME im struggling to format it properly. I basically pull the date from the database, convert it using strtotime(), then convert it to a date using date(). The problem is that when i use 'a' to display am/pm the time almost always says am. If the time is 11am then it will display 11am. If it's 12pm then it will display 12pm, but if it comes to 1pm and above it will revert back to 1am. This is the date string I use: date('jS M Y g:i a'); is this due to the fact that mysql DATETIME uses 24 hour clock ('H'), if so is there a way around this? Hi, I have a textarea called registerDomain which i enter multiple domain names into (separated by a new line) e.g. www.google.com www.sky.com www.bt.comI have the following code to get each of the domains and format them like google.com (lowercase without any spaces) sky.com (lowercase without any spaces) bt.com (lowercase without any spaces)The below code I have works perfectly, however its awful to look at. I wondered if anyone could advise on a cleaner/more elegant way of achieving this. Thanks, if (isset($_POST['submit'])) { $values = trim($_POST['registerDomain']); $array = explode("\n", $values); $array = array_filter($array, 'trim'); foreach ($array as $line) { $domain = addslashes($line); $domain = preg_replace("/\r|\n/", "", $domain); $domain = strtolower($domain); $domain = str_replace("www.", "", $domain); $domain = str_replace(" ", "", $domain);
I'm going round in circles with this one, but I have a feeling that the answer is obvious. I have POST information that I want to use as a date and display it using date format, but I don't know how to The POST data outputs the following: 2011-9-23 Assuming I have defined $date as the posted data from the previous form, how do I write some code to tell it to output it as September 23, 2011, or just Sept 2011? Hi, I want to chenge the following statement so that numbers ending with ".00" are changed to blank. Many opinions but I haven't got any to work. Any help? <td align=right class="currency">$'.number_format($row['value1'],2).'</td> This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=346474.0 So I have this page that outputs a sql query for required courses (healthcare field) and creates an email based on user input (variable). The email sends and I receive the information but the format is jacked up. My markup in the email shows. As an example, I should be getting this. Course Date Mandt Recert 1/16/2011 AWMD Recert 9/15/2010 etc, etc. What I currently get in the email is this: <table width=100% class="style11"><th align="left"><u>Course</u></th><th align="left"><u>Complete By</u></th><th align="left"> <th><tr><td width=33%>Abuse Neglect and Exploitation</td><td width=10%>12-31-1997</td><td width=33%></td></tr><tr><td width=33%>BloodBorne Pathogens Video</td><td width=10%>04-18-2008</td><td width=33%></td></tr><tr><td width=33%>MANDT Recert</td><td width=10%>08-11-2010</td><td width=33%></td></tr><tr><td width=33%>AWMD Recert</td><td width=10%>06-28-2011</td><td width=33%></td></tr><tr><td width=33%>CPR/1st Aid Combo</td><td width=10%>07-16-2012</td><td width=33%></td></tr></table></body></html> <?php //connect to the database include 'dbcommon.php'; $conn = mysql_connect($dbhost, $username, $password) or die("Could not show the required classes." . mysql_error($conn)); mysql_select_db($dbname); //grab the classes that are required $query="SELECT course, date_last_taken, certification FROM course_completions WHERE employee_id='" . $_REQUEST['employid'] . "' order by date_last_taken asc"; $rs = mysql_query($query, $conn); $numrequired = mysql_num_rows($rs); $emailtext .= "<table width=100% class=\"style11\">"; $emailtext .= "<th align=\"left\"><u>Course</u></th><th align=\"left\"><u>Complete By</u></th><th align=\"left\"> <th>"; if ($numrequired == 0) { $emailtext .= "<html>\n"; $emailtext .= "<body>"; $emailtext .= "<tr><td colspan=3>No classes required</td></tr>"; } while ($results = mysql_fetch_array($rs)) { $emailtext .= "<tr>"; $emailtext .= "<td width=33%>"; $emailtext .= $results["course"]; $emailtext .= "</td>"; $emailtext .= "<td width=10%>"; $emailtext .= date("m-d-Y",strtotime($results["date_last_taken"])); $emailtext .= "</td>"; $emailtext .= "<td width=33%>"; $emailtext .= "</td>"; $emailtext .= "</tr>"; } $emailtext .= "</table>"; $emailtext .= "</body>"; $emailtext .= "</html>"; echo $emailtext; mysql_close($conn); $headers .= "MIME-Version: 1.0\n"; $headers .= "Content-Type: multipart/alternative; boundary=\"$mime_boundary\"\n"; //email the results/ $email = $_REQUEST["email"]; $comment = "message1"; $subject = " ARCA Required Courses "; $message = $emailtext; mail($email, $subject, $message); if ($mail) { echo "Email sent, click <a href=displaycourses.php?" . SID . ">here</a> to return."; } else { echo "There was a problem sending the email."; } ?> I'm sure the syntax isn't correct somewhere but I need help with the output of the email formatting. Thanks! Hi, When I do this the result is a date of zeros? $DateAndTime = date('d-m-y', strtotime($DateAndTime)); All I want is a date in format of DD0MM-YYY and the Time in HH:MM::SS Any help would be great! I know it is basic, Thanks in advance Please help me sort out the syntax for this Code: [Select] <?php echo '<a href="/u/${user_info["username"]}"><img src="', getUserAvatar($user_info['username']), "\" class=\"avatar f_left small\" title=\"${user_info['display_name']}\" alt=\"${user_info['display_name']}\" /></a>"; ?> I want a little online users list at the bottom of my page and the color of the username is to match the color defined in the database. but how do i get them to align side by side? if i add them to a <p> they will all appear under neath each other. Heres my current code: $sql=mysql_query("SELECT * FROM ".DB_PREFIX."members WHERE online = 1"); while ($row = mysql_fetch_object($sql)) { echo '<p style="color: #'.$row->username_color.';">'.$row->username.'</p>'; } also i want a comma at the end of each but how do i stop it adding a comma to the end of the last one? Hi all Been trying to get my head around formatting a string, and struggling. I have a serious of numbers held in a DB and I need these to display as 5 figure numbers. if the DB held the record "48" I would need this to be displayed as "00048". Can anyone give me a clue. I've tried reading the php manual but this just confuses me more. |