For one of our projects we need a value input that supports number localization in IE, and as can be seen here (link) IE doesn't support comma separation. To work around this issue I figured to make a dropdown that has all values with commas.
I've run into a strange problem in automatically generating this range. It works for all values except 0. I hope there is a solution out there (or a logical explanation) to solve or help me understand this strange behaviour.
The code I use:
$select_number = "";
for ($i = 10; $i >= 0; $i -= 0.1){
$value = str_replace(".", ",", $i );
$select_number .= "<option value='" . $value . "' $selected>" . $value . "</option>";
}
this code is placed in the interface with
<select class="form-control" id="myname" data-live-search="true" name="myname">
<?php echo $select_number; ?>
</select>
This renders the the following dropdown
Notice that 0 became 1,87905246918E-14. If I change the order of the for loop to for($i = 0; $i <= 10: $i += 0.1) everything works fine... Anybody know a solution to this?
I use php version 5.6.28
Loop through the integers instead:
$select_number = "";
for ($i = 100; $i >= 0; $i -= 1){
$value = str_replace(".", ",", $i/10 );
$select_number .= "<option value='" . $value . "' $selected>" . $value . "</option>";
}
Floating-point numbers suffer from round-off error.
Related
I want to update the variable outside of the foreach scope and use it again in the condition inside it, but the variable in condition stays the same with the initial value. It gets updated outside, but the condition inside still uses the old value for comparing. How can the variable inside, used in condition get updated as well?
$total = 5.00000008;
for($i = 0; $i < count($values); $i++) {
if($total == $values[$i]){
$total += 0.00000001;
}
}
I am referring to the $total variable inside if condition, it doesn't get updated.
In a comment, #NanThiyagan wrote:
"your question was not clear.but your code works fine refer
eval.in/1050113"
Check out the output. It says 5.0000001. This might give you a hint that php automatically does something to round up your value.
Read this: http://php.net/manual/en/language.types.float.php
And pay attention to the part:
"So never trust floating number results to the last digit, and do not
compare floating point numbers directly for equality."
In this article they approach the problem with an implicit precision: https://www.leaseweb.com/labs/2013/06/the-php-floating-point-precision-is-wrong-by-default/
Like this:
ini_set('precision', 17);
echo "0.1 + 0.2 = ". ( 0.1 + 0.2 ) ."\n";
$true = 0.1 + 0.2 == 0.3 ? "Equal" : "Not equal";
echo "0.1 + 0.2 = 0.3 => $true\n";
I think you might not be fully aware of what's happening inside the loop.
The variable $total is being updated every time the condition is true. And the condition variable $total is updated as well.
Here's an example so you can see it happening:
$values = [5.00000008, 5.00000009, 5.00000007];
$total = 5.00000008;
for($i = 0; $i < count($values); $i++) {
echo ((string) __line__ . ' => ' . (string) $total . " (current total)\n");
if($total === $values[$i]){
echo ((string) __line__ . ' => ' . (string) $total . " (before increment)\n");
$total += 0.00000001;
echo ((string) __line__ . ' => ' . (string) $total . " (after increment)\n");
}
}
And here's the code tested: https://3v4l.org/EJkNG
I am referring to the $total variable inside if condition, it doesn't get updated.
Of course it gets updated.
Simply echo $total inside the loop to find out.
<?php
$values = [5.00000007, 5.00000008, 5.00000009];
$total = 5.00000008;
for ($i = 0; $i < count($values); $i++) {
if ($total == $values[$i]) {
$total += 0.00000001;
}
echo $total . "\n";
}
Output:
5.00000008
5.00000009
5.0000001
See for yourself at https://3v4l.org/RBHa3
I am trying to increment two separate numbers in the same for loop. For example I want the first number to be:
0,2,4,6,8,10 etc
I want the second number to be:
1,3,5,7,9 etc
I have tried what was suggested here but could get it to work:
How to increment a number by 2 in a PHP For Loop
My code so far:
$count = count($toyList);
echo $count;
for($i=0; $i<$count; $i++){
$json = '{"toy": {"toyname":"' . $toyList[$i+2] . ',"status":"' . $toyList[$i+3] . '"}}';
}
Any help would be greatly appreciated. Thanks.
Introduce an additional variable and increase that inside the loop after you have done with it whatever you intend to do. I don't have an environment for PHP at hand, but it should look something like this:
$count = count($toyList);
echo $count;
$j = 1;
for($i=0; $i<$count; $i++){
$json = '{"toy": {"toyname":"' . $toyList[$i+2] . ',"status":"' . $toyList[$i+3] . '"}}';
$j = $j + 2;
}
I need to update tags column so each cell has the content like this:
2-5-1-14-5
or
3-9-14-19-23
or simmilar (five integers, in range from 1-25).
id column is not consecutive from 1-117, but anyway min id is 1 and max 117.
$arr = [];
$str = '';
$id = 1;
for ($x = 1; $x <= 25; $x++){
array_push($arr, $x);
}
while ($id < 117) {
shuffle($arr);
array_splice($arr, 5, 25);
foreach ($arr as $el){
$str .= $el . '-';
}
$str = rtrim($str,'-');
$db->query("update posts set tags = '" . $str . "' where id = " . $id);
$id += 1;
}
I'm not sure how to describe the final result, but it seems that the majority of cells are written multiple times.
Any help ?
To combine my comments into one piece of code:
$full = range(1, 25);
$id = 1;
while ($id < 117) {
shuffle($full);
$section = array_slice($full, 0, 5);
$str = implode('-',$section);
$db->query("update posts set tags = '" . $str . "' where id = " . $id);
$id += 1;
}
So the reset of $str is not needed anymore since I have inserted the implode() where it seems functional. The other bits of code could probably be improved.
Two warnings:
Using PHP variables directly in queries is not a good idea. Please use parameter binding. This particular piece of code might not be vulnerable to SQL-injection but if you do the same elsewhere it might be.
Your database doesn't seem to be normalized. This might cause trouble for you in the long run when you expand your application.
I've got one nagging little bug in this script. I'm going through my cart items and passing them into hidden inputs. The cart_id ($obj->id) is working fine into the value="" but my iteration loop that gives each value a unique name="" (cart_id_1, cart_id_2 etc) is NOT iterating.
<?php
$pass_cart_q = "SELECT c.id FROM carts AS c WHERE c.user_session_id='$sid'";
$result = $mysqli->query($pass_cart_q);
$i = 1;
while ($obj = $result->fetch_object()) {
echo "<input type=\"hidden\" name=\"cart_id_".$i."\" value=\" .$obj->id. \"><br>";
$i = $i++;
}
mysqli_close();?>
Each name field is coming through as cart_id_1
$i=$i++;
That's the problem just do:
$i++
Please replace $i = $i++; with just $i++.
$i = 1;
$i = $i++;
echo $i, "\n"; // 1
$i = 1;
$i = ++$i;
echo $i, "\n"; // 2
$i = 1;
$i++;
echo $i, "\n"; // 2
$i = 1;
++$i;
echo $i, "\n"; // 2
What $i = $i++ will cause it literally this: "make $i equal to $i and then increase it by one", but the $i will still remain the same. To solve this, simply replace $i = $i++; with $i++.
Manual Entry
you are assigning the incremented value to $i variable. and hence it is not able to iterate. instead you should remove that assignment variable $i and it should only be $i++
I randomized a set of questions using the following code:
for($i=0; $i < count($nwi); $i++)
$itemorder[$i] = $i;
shuffle($itemorder);
$_SESSION["itemorder"] = $itemorder;
A few pages later, a portion of the questions are presented:
for ($i=0; $i<40; $i++) {
if ($i % 10 ==0) echo $header;
echo '<tr class="';
if(in_array($itemlabel[$_SESSION["itemorder"][$i]], $errors)) echo 'skip';
elseif ($i % 2 == 0) echo 'even';
else echo 'odd';
echo '">';
echo '<td>' . ($i + 1) . ".</td><td>" . $itemtext[$_SESSION["itemorder"][$i]] . '</td>';
for ($j = 1; $j <= 6; $j++) {
echo "\n" . '<td';
if ($j == 6) echo ' style="background-color:#999;"';
echo '><input type="radio" name="';
echo $itemlabel[$_SESSION["itemorder"][$i]];
echo '" value="';
echo $j; //value of the input
echo '"';
if ($_POST[$itemlabel[$_SESSION["itemorder"][$i]]] == $j) echo " checked";
echo '></td>';
}
At the end of the survey, I am trying to put the answers to the questions (which should range in value from 1-8) into my SQL database:
"INSERT INTO surveydata
(id, agree_pppg_01,agree_pppg_02,agree_pppg_03,....
VALUES
('$_SESSION[id]', '$_SESSION[itemorder][0]',
'$_SESSION[itemorder][1]', '$_SESSION[itemorder][2]',
'$_SESSION[itemorder][3]',...
I am getting only zeros in my SQL database regardless of how I answer the questions. Any suggestions?
Well, first I don't see anything assigning anything to the session values, but the issue with your code is in this pattern: '$_SESSION[itemorder][1]'. First, I would make sure that MySQL is expecting a varchar there and not an int. If it is an int, good form would be to make sure it isn't quoted.
More importantly, though, when you have an associative array in PHP, you need to make sure PHP expects that.
This
$a = array("hi"=>array("world"=>0)); echo "$a[hi][world]";
Outputs
Array[world]
Put braces around the lookup to make sure it knows to treat it as an array, and then put quotes around all string indexes:
// note the braces and quotes
$a = array("hi"=>array("world"=>"here")); echo "{$a["hi"]["world"]}";
Outputs
"here"
But, I wonder if you wouldn't be better off just using implode:
$columns = implode(',', $_SESSION['itemorder']);
$query = "INSERT INTO surveydata
(id, agree_pppg_01,agree_pppg_02,agree_pppg_03,....
VALUES ('{$_SESSION["id"]}', $columns )";
I do feel obliged to point out that that system does not seem scaleable, and column names like agree_pppg_02 are not descriptive. You may want to go to the codereview stackexchange site to see if they can't offer tips on database design.