I'm having a problem with PHP in_array() method, it is quite simple but not working as it should. I've tried many solutions from the internet. But everything seems okay. Can you please help me find a mistake in my syntax or logic
Here is my code
$array1 = array('1','0.2','1.3','0.6','1.4','1.6','12','1.2','11.2');
$array2 = [];
for($i=0.1; $i<=15;){
$array2[] = $i;
$i+= 0.1;
}
foreach($array2 as $key=>$value){
// print_r($array1);
if(in_array($value, $array1)){
echo $value. ' OK <br>';
}else{
echo $value. '<br>';
}
}
Red Highlighted text is returned true and green is not returning
My Answer:
The issue you are facing is due to the way floating-point numbers are represented in PHP. When you compare floating-point numbers for equality, you may encounter precision issues.
In your code, you are comparing floating-point numbers in `$array2` with string values in `$array1`. When using `in_array()` function, it performs a loose comparison, which may not work as expected for floating-point numbers.
To fix this issue, you can convert the string values in `$array1` to floating-point numbers before comparing them. Here is an updated version of your code:
php
$array1 = array(1, 0.2, 1.3, 0.6, 1.4, 1.6, 12, 1.2, 11.2);
$array2 = [];
for ($i = 0.1; $i <= 15; $i += 0.1) {
$array2[] = $i;
}
foreach ($array2 as $value) {
$found = false;
foreach ($array1 as $num) {
if (abs($value - $num) < 0.0001) {
$found = true;
break;
}
}
if ($found) {
echo $value . ' OK
';
} else {
echo $value . '
';
}
}
In this updated code, we are converting the string values in `$array1` to floating-point numbers before comparing them with the values in `$array2`. We are also using a small tolerance value (0.0001) to account for precision issues when comparing floating-point numbers.
This should help you get the desired output with the correct values being identified as present in the array.
Rate this post
5 of 5 based on 6322 votesComments