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

Thank you at Advance.

+4
source share
2 answers

If you want to combine two arrays, you should use array_intersect()here.

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

<?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 the manual: in_array - checks if a value exists in the 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()how you can do it:

<?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:

, , array_intersect(), , :

<?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

+4

array_intersect, count, , ...

array_intersect

:

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>";
        }

}

+1

Source: https://habr.com/ru/post/1660261/


All Articles