PHP - Problem With Casting From Strings To Integer
<?php
$temp = "01"; $temp = (int)temp; echo $temp; ?> I am using above code to convert string to integer variable but i am getting incorrect output.. somehow casting chopping values in the string. for example, above code should give me output 01 but actual output is 0. any pointer? i am new to php... Thanks, Rajesh Similar TutorialsHello guys, I have a form where you can select a score between 0 and 10(only integers).
I want to check if the value that I recive, is integer.
Im using this code(exemple):
$integer = intval($_POST["p1"]); if(is_int($integer)){ echo 'INT'; } else { echo 'NO INT'; }My problem is that if it recive letters, the conversion converts it to 0, and it says that it is integer. So with this method I should discard the 0. You guys know a method to avoid that? Thank you guys I want to round off an integer vaule to 10-6 grd from 52.71666666 to 52716666 0.926888888 to 926888 does anyone know a simple way to do this? So I am trying to take a string value of dollars (posted from a form) and times it by 100 to get the cents Integer value of the dollars. For some reason if I do this with something like 278.53 I end up with 27852. Same concept for 278.59 ends up as 27858. I don't understand why or how to make it work. I've tried many things and nothing has made it work. $price = '278.53'; // posted from the form $cents = $price * 100; // converting to cents. end_result = (int)$cents // This will end up being 27852 not 27853.
Ive got a simple function that's counting percentages of the results, and what I want is when the first line does $variable / 100 - to go on 2 decimals(ex. 0.72142141 what I want is to write 0.72). Code: [Select] function postotak(){ $p = $bodovi / 100; $postotak = $p * 100; 0 down vote favorite Hi Guys! I have a method that get's all devices that share a specific ID. Foreach of those device UID's, I am trying to send a APN (Apple Push Notification) using the easyAPN's class. The method that is having the problem is $apns->newMessage($id); It seems to think I am not passing a valid integer for $id. The $id is an array like so Array ( => 1 ) I have also tried passing just the value of the array like so $apns->newMessage($id[0]). No matter what I do.. I keep getting this error... "Notice: TO id was not an integer. 1) Messages_model::send_apns -> File: sendMessage.php (line 28) 2) APNS::queueMessage -> File: messages_model.php (line 195) 3) APNS::_triggerError -> File: class_APNS.php (line 599)" Here is my method... please let me know where I've gone wrong with the $id. function send_apns($data) { include 'apn_classes/class_DbConnect.php'; include 'apn_classes/class_APNS.php'; $message = new Messages_model(); $db = new DbConnect(); $db->show_errors(); $apns = new APNS($db); //get uid's for aid $sql = "SELECT `devices`.`uid` FROM `devices` WHERE `devices`.`aid` = '".$data['target']."'"; //echo $sql; $query = mysql_query($sql); if(mysql_num_rows($query)) { while($uid_data = mysql_fetch_array($query)) $uids[] = array( "uid" => $uid_data['uid'] ); } //make sure there is a uid if(!empty($uids)) { //check the device apn pid foreach($uids as $uid) { $sql = "SELECT `apns_devices`.`pid` FROM `apns_devices` WHERE `apns_devices`.`deviceuid` = '".$uid['uid']."'"; //echo "$sql"; $query = mysql_query($sql); if(mysql_num_rows($query) > 0) { while($pid_data = mysql_fetch_array($query)) { $pids[] = array( "pid" => $pid_data['pid'], ); if(!empty($pids)) { foreach ($pids as $pid) { $id = array($pid['pid']); print_r($id); //Send APN $apns->newMessage($id[0]); $apns->addMessageBadge(128); $apns->addMessageAlert($data['message']); $apns->addMessageSound('chime'); //$apns->addMessageCustom('acme2'); $apns->queueMessage(); $apns->processQueue(); } } } } } } else { echo "Device Does not Exist"; } } Hi i'm trying to get out a sub string from multiple pages where i'm using a start point string that looks like this "(integer)" where "integer is different every time. Is there any way I can tell it that its just an integer there so if its "(3)" on one page and "(10)" on another page it will start from the same spot? Hey, I have this brainstorm whether I should store id's as integers or text? I mean in my database, since my IDs start from like 1319129364 which is a rather large number, I was thinking if it would be better to save it as text? Which case requires less memory ? how can i convert string type into integer like when using parseInt in javascript...however i use (int)$string but not working i have this $string1="10"; $string2="5"; and i wish to add both string ....using (int) still treat $string1 and $string2 as string so i get 105 as a result instead of 15 This is a cross between HTML, PHP, and MySQL. I'm not exactly sure which to blame (other than myself of course) I'm collecting a bid price in a standard form <input type="number" name="maxbid" value="<?php echo $maxbid ?>"/> I have recalled the value from the database where I store it and display it in the field if it exists. If the field has never been entered, the field shows nothing. It's not required that a bid be entered. There are other fields of data that may be updated and this field is left blank. On the page called by the submit button I'm retrieving the fields $maxbid=$_POST[maxbid]; Then I store the fields in the database either with an INSERT or an UPDATE if(mysql_num_rows(mysql_query("SELECT id FROM data WHERE id = '$id'"))) { echo "Updating....."; mysql_query("UPDATE data SET maxbid='$maxbid', name='$name' where id='$id'"); } else { echo "Inserting....."; mysql_query("INSERT INTO data (id, maxbid,name) VALUES ('$id','$maxbid',$'name')"); } I know I'm not handling the Numeric values correctly, and I'm having a hard time finding the correct method for doing so. Right now, if the name is entered byt the maxbid is left blank, nothing gets inserted or updated. if I enter both the maxbid and the name it works. I can't have maxbid show up as a 0, I need it to be blank if nothing is entered. Also when I check $maxbid, it's not an INTEGER (per INTVAL) when I check it, even though maxbid in the table is an INTEGER. When I pass it around, it seems to lose it's INTEGER value, but still shows as a number. I know this sounds confusing, heck I'm confused. If someone could point me to a good tutorial, I'd figure it all out, but most tutorials don't get into the data type that much, and the combination of the form, passing the variables, reading the values from the database, etc. is what's causing me grief. Any guidance would be appreciated. I am making a online Bible with search function. I was able to do the boolean search for text keywords without much trouble. Now I want a user to be able to type in an exact verse into search form and have that verse display in results. IE: User types in John 3:16 and search result displays that verse. The following works if the user types John:3:16. I cannot figure out how to do this without requiring the user to type a : after book name. Code: [Select] if($search_type=='verse'){ $query2 = explode(":", $query); $bookquery = $query2[0]; $chapterquery = $query2[1]; $versequery = $query2[2]; $result4 = $db->sql_query("select * FROM Bible$version WHERE book = '$bookquery' AND chapter= '$chapterquery' AND verse ='$versequery'"); while ($row = $db->sql_fetchrow($result4)) { $book = $row['book']; $chapter = $row['chapter']; $verse = $row['verse']; $scripture = $row['scripture']; echo "<b><a href=\"modules.php?name=Bible&call=chapter&viewbook=$book&viewchapter=$chapter&version=$version\">$book</a> $chapter:$verse</b>"; echo "<br>"; echo "$scripture"; echo "<hr>"; } if(!$query){ echo "<b>You did NOT enter any keywords.</b><br>"; } if(!$scripture){ echo "<b>No results found.</b>"; } } } Is there a function to find first integer in the string and insert a : before it? When I post the data to mysql I want to submit the value as an integer. How can I make this $12,000 be 12000? Hey, I am echoing out: Code: [Select] $source = implode(',', $arr2); echo $source; which is a array, and it echo's out: "2,2,2" I am trying to find a php function to add each array, so the result will be "6". Possible? How can I modify the following code to not display $hash_row['total'], but to display the sum of the counted "total" value + 1? Is there a way that I can assign that variable in the "select query" area (for instance, "COUNT(hr.hasher_id) + 1 as total1"), and then call $hash_row['total1] in the result table? I'm not sure if the syntax exists to add an integer value to a COUNT value and assign to a new variable... Code: [Select] <?php include "modules/dbase_connection.php"; #create MySQL connection $sql_connection = sql_connect("blah","blah","blah","blah"); # select the Hashers and hashes by total number<br /> $hash_query = " SELECT ha.*, COUNT(hr.hasher_id) as total FROM hashers as ha, hash_records as hr WHERE hr.hasher_id = ha.hasher_id GROUP BY hr.hasher_id ORDER BY total DESC "; $hash_result = mysql_query($hash_query) or die(mysql_error()); $x = 1; while($hash_row = mysql_fetch_array($hash_result)) { #display the table header if($x == 1) { echo ' <br /> <table align="left"> <br /> <tbody> <tr><br /><td colspan="2"><strong>Potential On-Sec</strong></td><br /></tr>'; $x++; } echo '<tr><br /><td>' . $hash_row['hasher_name'] . '</td><br /><td>' . $hash_row['total'] . '</td><br /><td>- ' . $hash_row['real_name'] . '</td><br /></tr>'; } echo '</tbody></table></td><br />'; ?> Hi, not sure if this is posted in the right place (think it should be in the Regex section ) but hopefully someone can help me out a bit. I have the following string for example which is stored in a variable called $var. Quote This is a reference [ref=17][/ref] number I wish to extract only the number after the equals sign and store it as a variable. So I am using the following code to do so: $ref_num = preg_replace("/.*?\[ref\=(.*?)\]\[\/ref\].*?/is", "$1", $var); The only problem is, I can omit the text before the integer and the tags themselves but I still get the text after the [/ref] section and I cannot get rid of it. It seems my .*? placed after it doesn't work like it does at the beginning. Can anyone offer any help at all, it will be greatly appreciated - I'm fairly new to using Preg_replace so I still don't know how best to form Regular Expressions. Thanks, Dan EDIT- I have found a workaround which I will post below - however I would still like to solve it the way I planned originally which is the way I posted here. Here's what I did - because I know the integer is never going to be more than 5 characters long, I used the replace from before but added a substring like so. $ref = substr(preg_replace("/.*?\[ref\=(.*?)\]\[\/ref\]/is", "$1", $var),0,5); This grabbed the first 5 characters whether it was a number or not, then I used this to strip any non-numerical characters. Finally I added an intval to convert it to an integer rather than a string. $ref = intval(preg_replace ('/[^\d\s]/', '', $ref)); I have an integer that I'd like to validate to ensure that it is a valid number between 1 and 99999999999999999999(20 digits). I'm thinking about using the following, but I'm not sure what the max range is on the FILTER_VALIDATE_INT options. return filter_var($_REQUEST['r'], FILTER_VALIDATE_INT, array("options" => array("min_range"=>1, "max_range"=>99999999999999999999))); Hey, Im trying make a way to check an input to make sure it only consists of "1,2,3,4,5,6,7,8,9,0 and . " I thought i could explode the number and check it to an array that has "1,2,3,4,5,6,7,8,9,0 and . " I havent worked with arrays before so i dont quite know how they work or to go about this? Any ideas cause im sure im not the first to ask for something like this Thanks Hi, I'm by no means an expert in php but I use and continually try and figure out how to update some very old soccer stats scripts that break from time to time when newer versions of php are released. Anyway, I would appreciate any pointers with this error please: Warning: mysqli_query() expects parameter 3 to be integer, object given in /blah/blah/blah.php on line 81 The code is: 79 - mysqli_query($connection,"INSERT INTO seasons SET 80 - SeasonID = '$seasonid', 81 - SeasonPlayerID = '$player_id'",$connection) 82 - or die(mysqli_error($connection)); Server is running php 7.2.28 Thanks in advance. Hi there, I am working on an associative array: The array is: $currentIds //when we do print_r($currentIds); //it returns value 41 and 42. Array ( [0] => [1] => 41 [2] => 42 [3] => ) Which is OK but I have to use these two values in an SQL query but they are in Array forms. I need to convert them to integer to be able to use them in SQL query. Please let me know how I can convert this Array to Integer so that i can use the integer values for my SQL statement. Thank you All comments and feedback are always welcomed Cheers! Hi, When I run the following code... <?php if ($_GET['view']) { echo 'test'; } .. and then navigate to index.php?view=1 the above code outputs 'test', as intended. The same goes for any non-zero value after the ?view= However, navigating to index.php?view=0 does not work as intended because it assumes that the 0 is FALSE. So if I modify the code, like this: <?php if ($_GET['view'] || $_GET['view'] == 0) { echo 'test'; } ... it outputs 'test' even when view is not set, i.e. when I navigate to index.php without the ?view=. Is there an easy way to force the value to behave as an integer instead of boolean? I have tried putting (int) before, as well as the intval() function, but neither seem to work. Thanks. This topic has been moved to PHP Math Help. http://www.phpfreaks.com/forums/index.php?topic=333872.0 |