简体   繁体   中英

How to compare two array in php

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 value of $arr is equal to the value of $field.

Thank you in Advance.

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

compare two array by array_intersect then check with count to know matches array value has...

array_intersect

Compare the values of two arrays, and return the matches:

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 (count(array_intersect($arr, $field)) > 0) {
            echo "<script>alert('duplicate array')</script>";
        }else{
            echo "<script>alert('something to do')</script>";
        }

}

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.

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