Why is the loop printing wrong value? [duplicate] - php

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 3 years ago.
The parameter for index 5 needs to be 0 in below code.
But The value for echo($a[5]) comes 1.2325951644078E-32.
The loop prints correct values for all other parameters except for 5th index (which needs to be 0 according to me).
Can anybody tell me why is that happening??
for($x=-2;$x<2.1;$x+=0.4){
$a[] = $x*$x;
}
echo($a[5]); //this is not printing 0 why?
Output is:-
Array
(
[0] => 4
[1] => 2.56
[2] => 1.44
[3] => 0.64
[4] => 0.16
[5] => 1.2325951644078E-32
[6] => 0.16
[7] => 0.64
[8] => 1.44
[9] => 2.56
[10] => 4
)

it should be zero..
Modify your code like this and try..
$a[] = number_format($x*$x,2);

Bro you forget to convert to number format before math.
for($x=-2;$x<2.1;$x+=0.4){
$a[] = number_format($x)*number_format($x);
}
echo($a[5]); // 0
Hope help this.

Related

Why this isn't working ? Php Array Auto Replace Values and short Array

Hi I need to select a rand value in the array removed and short the array i came out whit this small code but it keeps in an infinite loop but this is the weird look
<?php
$array=array("1","2","3","4","5","6","7","8","9","0");
$count=count($array);
for ($il=1;$il<=$count;$il++){
$array_value=array_rand($array, 1);
$array_value_key = array_search($array_value, $array);
$array_key_last=array_key_last($array);
for($if=0;$if<=$array_key_last;$if++){
if ($if==$array_value_key){
for($ia=$array_value_key;$ia<=$array_key_last;$ia++){
if ($ia<$array_key_last){
$ian=$ia+1;
$array[$ia]=$array[$ian];
}else{
unset($array[$ia]);
}
}
}
}
print_r($array);
}
?>
there the output can be different each time likes this but never ends
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 5
[4] => 6
[5] => 7
[6] => 8
[7] => 9
[8] => 0
)
Array
(
[0] => 2
[1] => 3
[2] => 5
[3] => 6
[4] => 7
[5] => 8
[6] => 9
[7] => 0
)
^C
and i have to break it but as you can see in the first loop work as expected removes the number 4 and in the second loop removes the number 1 but don't finish the third loop
I have reviewed many times and get in to the conclusion of the problem it is on the line
$array[$ia]=$array[$ian];
if i add a echo here get printing a number it self to the infinity why?
$array[$ia]=$array[$ian];
echo $array[$ia],"\n";
The Problem is not in one line. It takes a few commands to interact:
array_rand returns the key of the element not the value
array_search returns (bool)false if it doesn't find the value (because of 1 this can happen)
You use $array_value_key to start a for loop. Because of 2 it can be (bool)false.
When you increment a boolean, it does not change. I.e. your $ia++ does nothing.
That's why $ia<=$array_key_last will never turn false and your loop runs forever.

usort of session array not outputting as expected

I have a grid of img squares that can be dragged into any order using the sortable library. Each img is a visual representation of a result from a mySQL db query that selects any image that shares an 'imageparent' identifier. The order they're presented in the grid is taken from the 'imageorder' column in the database and starts at 0 and works in sequence up to the nth number of images returned.
The purpose of dragging the img grid is to be able to change the 'imageorder' index. On completion of the drag, the sortable library POSTS an 'imageorder' var by ajax to service.php and is received correctly. So rather than the original 0,1,2,3,4,5,6,7 order of the original, it sends a string like 2,1,0,3,4,5,7,6. Not too hard to grasp. After I switch the order the orderList var sent to service.php is always correct, but the array I end up sending to the db and setting as my session var becomes a little garbled in order after the second or third drag and I'm not quite sure why.
Code Examples and Comments
$_SESSION['selectedCsImages'] Array structure:
[0] => Array
(
[imagename] => "Title"
[imageorder] => 0
[imageid] => 43
)
[1] => Array
(
[imagename] => "Title"
[imageorder] => 1
[imageid] => 21
)
[2] => Array
(
[imagename] => "Title"
[imageorder] => 2
[imageid] => 3
)
etc...
Services.php extract:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Turn the orderList posted into an array
$removeChars = array('"','[',']');
$orderList = str_replace($removeChars, "", $_POST['order']); // POST received fine.
$listArray = explode(",",$orderList);
// Retrieve the session array
$sorting = $_SESSION['selectedCsImages'];
/* My logic is that I compare the $sorting array to $listArray and reorder $sorting by 'imageorder' to match $listarray */
usort($sorting, function($a, $b) use ($listArray) {
return array_search($a['imageorder'], $listArray) - array_search($b['imageorder'], $listArray);
});
/* I now have a $sorting array that (sometimes, hence the problem) matches the order that the images had just been dragged into by the user. Typically, as I mentioned above, it's correct after the first drag, but not always after the second or third where it creates a new order that I can't see a pattern or logic in. */
/* Had there not been errors with the usort function, I (would) have a $sorting array in the order I want but with imageorder values referring to pre-sorting. I iterate through the array and set each key to 0, 1, 2, etc. so that I have an array in the correct order and with each imageorder correctly stating its place.*/
$i = 0;
foreach ($sorting as $key => $value) {
$sorting[$key]['imageorder'] = $i;
$i++;
}
/* The information is attempted to be sent to the db and, on success I update the session var */
// Database code (runs succesfully and updates the db as per the image orders found in the $sorting array)
$_SESSION['selectedCsImages'] = $sorting;
Debugging:
From debugging, it appears that something happens with the usort function when I call this page from ajax for the second or third time. Everything after this follows through fine and processes the correct or incorrect order as per expectations. The orderList var posted by sortable is correct each time. I'd provide a sample of the $sorted var after usort each time but it's as simple to describe it as the above array example in an order I didn't specify after dragging and I can't see a pattern in the seemingly random order it outputs.
From researching, I had thought that it was an issue with session vars being retained until the page is refreshed but it appears that the ajax call to services.php should refresh the $_SESSION['selectedCsImages'] var. I had also read that, perhaps, I was unknowingly using referenced array values and - as I source from a session var to a new array and, ultimately, save back to this session var from this array - I may have created some messy referencing feedback. However, I tried using $sorted = (array)clone(object)$_SESSION['selectedCsImages']; before attempting usort and the results didn't change.
PHP error logs are showing nothing.
Updates:
Per the suggestion of #Ayaou, I've checked the output of $listArray and am getting some unexpected results. I'd wrongly assumed that as the posted $orderList was correct, that the exploded array would not be a culprit.
Here's the output of print_r($listArray) after completing the following order swaps of 16 img elements: 1st with 2nd, 2nd last with last,6th with 7th:
1st and 2nd:
(
[0] => 1
[1] => 0
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
[10] => 10
[11] => 11
[12] => 12
[13] => 13
[14] => 14
[15] => 15
)
last and 2nd last:
(
[0] => 1
[1] => 0
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
[10] => 10
[11] => 11
[12] => 12
[13] => 13
[14] => 15
[15] => 14
)
6th with 7th:
(
[0] => 1
[1] => 0
[2] => 2
[3] => 3
[4] => 4
[5] => 6
[6] => 5
[7] => 7
[8] => 8
[9] => 9
[10] => 10
[11] => 11
[12] => 12
[13] => 13
[14] => 15
[15] => 14
)
I was progressing with the idea that $listArray would show a sequential 0,1,2,3,etc. each time with only the two swapped items showing order changes. As it's not, I'll look back again at $orderList and check if my sortable library is updating the orders it's obtaining correctly from the updated session var. Older order swaps are being retained somewhere along the chain where they shouldn't.
The solution is on your sortable form (on the front end), so instead of sending the imageorder on your 'order' post data, send the imageid index.
Then change your sort callback like this
//Use imageid index instead of imageorder
usort($sorting, function($a, $b) use ($listArray) {
return array_search($a['imageid'], $listArray) - array_search($b['imageid'], $listArray);
});

array_search() returning wrong key when the 0 int value is searched [duplicate]

This question already has answers here:
PHP in_array() / array_search() odd behaviour
(2 answers)
Closed 6 years ago.
I recently noticed trouble when using the array_search function in my code. I am searching the array "$allcraftatts" for the value "sharp". I tried to isolate the problem by setting up a two line experiment:
$testcopy=$allcraftatts;
$testsharp=array_search("sharp", $testcopy);
Using "print_r(get_defined_vars());" later on, I get this result:
[testcopy] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => Sharp Stone
[7] => Sharp Stones
[8] => stone
[9] => object
[10] => sharp
[11] => hard
[12] => 0
[13] => 0
[14] => 0
[15] => 0
[16] => 0
[17] => 0
[18] => 0
)
[testsharp] => 0
I made sure that I do not modify these variables at any other time.
Now, if I change my code to
$testcopy=$allcraftatts;
unset($testcopy[0]);
$testsharp=array_search("sharp", $testcopy);
it returns "1".
This leads me to believe that it always returns the first key in the array.
It baffles me! This is one of those bugs that makes you fear something wrong with the language itself. However doubtful this is, I actually was eventually driven to looking at the PHP source for something wrong there, but unfortunately could not understand it.
Seeing that it is a function simple as this, I will most definitely be completely humiliated by the inevitably simple answer, but at this point, I just want an answer.
array_search is using == to compare values during search
FORM PHP DOC
If the third parameter strict is set to TRUE then the array_search() function will search for identical elements in the haystack. This means it will also check the types of the needle in the haystack, and objects must be the same instance.
Becasue the first element is 0 the string was converted to 0 during search
Simple Test
var_dump("sharp" == 0); //true
var_dump("sharp" === 0); //false
Solution use strict option to search identical values
$testsharp = array_search("sharp", $testcopy,true);
^---- Strict Option
var_dump($testsharp);
Output
10
If any key before the searched one is numeric zero, then that key is returned, because it is performing a "loose" match dominated by the array's data type, and "sharp" (if converted to int) counts as zero. Using a strict checking, the correct value is found.
Otherwise, by executing
$testcopy = array_map('strval', $testcopy);
so that values are translated to strings, it works also with "loose" check.
Welcome to the wonderful world of loose typing. In php, array_search defaults to nonstrict comparisons ("=="), but you can add a third parameter to force strict ("==="). You almost always want strict, though there are times when nonstrict is the correct operation.
check out the following:
$allcraftatts = array(0, 0, 0, 0, 0, 0, "Sharp Stone", "Sharp Stones", "stone", new stdClass(), "sharp", "hard", 0, 0, 0, 0, 0,0 ,0);
$testcopy=$allcraftatts;
$testsharp=array_search("sharp", $testcopy);
$testsharpStrict=array_search("sharp", $testcopy, true);
print_r(get_defined_vars());
if(0 == "sharp"){
echo "true for == \n";
}else{
echo "false == \n";
}
if(0 === "sharp"){
echo "true for === \n";
}else{
echo "false === \n";
}
and the output:
[testcopy] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => Sharp Stone
[7] => Sharp Stones
[8] => stone
[9] => stdClass Object
(
)
[10] => sharp
[11] => hard
[12] => 0
[13] => 0
[14] => 0
[15] => 0
[16] => 0
[17] => 0
[18] => 0
)
[testsharp] => 0
[testsharpStrict] => 10
)
true for ==
false ===

Insert into ordered php array, move values

I have numbered array like
[0] => value 0
[1] => value 1
[2] => value 2
[3] => value 3
[4] => value 4
//keys 5-8 aren't set (I'm only demonstrating there could be a gap)
[9] => value 5
[10] => value 6
Is there any way to shuffle the array to move values when I add new to the specific position? So if i do something simillar to $array[1] = 'new value' it will change original value of 1 to new value of 2, 2 to 3 etc. up to 4 (then there is empty place in the example)?
Like this:
[0] => value 0
[1] => new value
[2] => value 1
[3] => value 2
[4] => value 3
[5] => value 4
[9] => value 5
[10] => value 6
Thank you very much for your help
Use array_splice .. Keep linear, not associated array, but places in array that need to be empty (for now) assign to null
Should work.
You could use the array_slice(). Check the examples below:
http://php.net/manual/en/function.array-splice.php

PHP array_search consistently returns first key of array [duplicate]

This question already has answers here:
PHP in_array() / array_search() odd behaviour
(2 answers)
Closed 6 years ago.
I recently noticed trouble when using the array_search function in my code. I am searching the array "$allcraftatts" for the value "sharp". I tried to isolate the problem by setting up a two line experiment:
$testcopy=$allcraftatts;
$testsharp=array_search("sharp", $testcopy);
Using "print_r(get_defined_vars());" later on, I get this result:
[testcopy] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => Sharp Stone
[7] => Sharp Stones
[8] => stone
[9] => object
[10] => sharp
[11] => hard
[12] => 0
[13] => 0
[14] => 0
[15] => 0
[16] => 0
[17] => 0
[18] => 0
)
[testsharp] => 0
I made sure that I do not modify these variables at any other time.
Now, if I change my code to
$testcopy=$allcraftatts;
unset($testcopy[0]);
$testsharp=array_search("sharp", $testcopy);
it returns "1".
This leads me to believe that it always returns the first key in the array.
It baffles me! This is one of those bugs that makes you fear something wrong with the language itself. However doubtful this is, I actually was eventually driven to looking at the PHP source for something wrong there, but unfortunately could not understand it.
Seeing that it is a function simple as this, I will most definitely be completely humiliated by the inevitably simple answer, but at this point, I just want an answer.
array_search is using == to compare values during search
FORM PHP DOC
If the third parameter strict is set to TRUE then the array_search() function will search for identical elements in the haystack. This means it will also check the types of the needle in the haystack, and objects must be the same instance.
Becasue the first element is 0 the string was converted to 0 during search
Simple Test
var_dump("sharp" == 0); //true
var_dump("sharp" === 0); //false
Solution use strict option to search identical values
$testsharp = array_search("sharp", $testcopy,true);
^---- Strict Option
var_dump($testsharp);
Output
10
If any key before the searched one is numeric zero, then that key is returned, because it is performing a "loose" match dominated by the array's data type, and "sharp" (if converted to int) counts as zero. Using a strict checking, the correct value is found.
Otherwise, by executing
$testcopy = array_map('strval', $testcopy);
so that values are translated to strings, it works also with "loose" check.
Welcome to the wonderful world of loose typing. In php, array_search defaults to nonstrict comparisons ("=="), but you can add a third parameter to force strict ("==="). You almost always want strict, though there are times when nonstrict is the correct operation.
check out the following:
$allcraftatts = array(0, 0, 0, 0, 0, 0, "Sharp Stone", "Sharp Stones", "stone", new stdClass(), "sharp", "hard", 0, 0, 0, 0, 0,0 ,0);
$testcopy=$allcraftatts;
$testsharp=array_search("sharp", $testcopy);
$testsharpStrict=array_search("sharp", $testcopy, true);
print_r(get_defined_vars());
if(0 == "sharp"){
echo "true for == \n";
}else{
echo "false == \n";
}
if(0 === "sharp"){
echo "true for === \n";
}else{
echo "false === \n";
}
and the output:
[testcopy] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => Sharp Stone
[7] => Sharp Stones
[8] => stone
[9] => stdClass Object
(
)
[10] => sharp
[11] => hard
[12] => 0
[13] => 0
[14] => 0
[15] => 0
[16] => 0
[17] => 0
[18] => 0
)
[testsharp] => 0
[testsharpStrict] => 10
)
true for ==
false ===

Categories