phparraysarray-intersect

Check if any value from a flat array exists in another flat array


while ($row = $update_post->fetch_array()){
    //Explodes checkbox values
    $res = $row['column_name'];
    $field = explode(",", $res);

    $arr = array('r1','r2,'r3','r4','r5','r6');

    if (in_array($arr, $field)) {
        echo "<script>alert('something to do')</script>";
    } else {
        echo "<script>alert('something to do')</script>";
    }
}

How to check if a value of $arr is equal to the value of $field.


Solution

  • If you want to match two array than you need to use array_intersect() here.

    If you want to check specific value with in_array() than you need to use loop here as:

    <?php
    $res = $row['column_name'];
    $field = explode(",", $res);
    $arr = array('r1','r2','r3','r4','r5','r6');
    foreach ($arr as $value) {
        if(in_array($value, $field))   {
            echo "success";
        }
        else{
            echo "failed";   
        }
    }    
    ?>
    

    According to manual: in_array — Checks if a value exists in an array

    Also note that, you have a syntax error in your array:

    $arr = array('r1','r2,'r3','r4','r5','r6'); // missing quote here for r2
    

    Update:

    If you want to use array_intersect() than you can check like that:

    <?php
    $arr1 = array('r1','r2');
    $arr2 = array('r1','r2','r3','r4','r5','r6');
    $result = !empty(array_intersect($arr1, $arr2));
    if($result){
        echo "true";
    }
    else{
        echo "false";
    }
    ?>
    

    DEMO

    Update 2:

    If you want to check which value are you getting by using array_intersect() than you can use like:

    <?php
    $arr1 = array('r2');
    $arr2 = array('r1','r2','r3','r4','r5','r6');
    $result = array_intersect($arr1, $arr2);
    if(count($result)){
        echo "Following ID(s) found: ".implode(",",$result);
    }
    ?>
    

    DEMO