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
You need to either use numbers or strings but not compare numbers to strings and hope that they will be the same. An easy fix would be to use strval
to convert the generated number to a string in the comparison test
<?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 $key=>$value){
if( in_array( strval($value), $array1 )){
echo $value. ' OK <br>';
}else{
echo $value. '<br>';
}
}
?>
You must compare a string array with a string, add a conversion before comparing or while you're initializing your second array.
This will solve your issue:
$array1 = array('1','0.2','1.3','0.6','1.4','1.6','12','1.2','11.2');
$array2 = [];
$i = 0.1;
while( $i <= 15 ) :
$array2[] = strval( $i );
$i = $i + 0.1;
endwhile;
foreach($array2 as $value){
// print_r($array1);
if(in_array($value, $array1)){
echo $value. ' OK <br>';
}else{
echo $value. '<br>';
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.