简体   繁体   English

我对 PHP in_array() function 做错了什么,它没有返回所需的值

[英]What am i doing wrong with PHP in_array() function, It is not returning desired values

I'm having a problem with PHP in_array() method, it is quite simple but not working as it should.我在使用 PHP in_array() 方法时遇到问题,它非常简单,但不能正常工作。 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>';
    }
    
}

Here is my output image这是我的 output 图像在此处输入图像描述

Red Highlighted text is returned true and green is not returning红色突出显示的文本返回 true,绿色没有返回

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一个简单的解决方法是在比较测试中使用strval将生成的数字转换为字符串

<?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>';
    }
    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM