简体   繁体   中英

How to compare 2 different length arrays to eachother

I'm trying to make a function that compares two different length arrays to each other and if they match then some actions are performed. Array1, cell1 compares to array2, cell1, cell2, cellN... Then Array1, cell2 compares to array2, cell1, cell2, cellN...

Something resembling this:

if(array1[$i]==array2[])
{
   // Some actions...
}

How can this be implemented?

PHP has in_array for searching an array for a particular value. So what about

foreach ($array1 as $search_item)
{
    if (in_array($search_item, $array2))
    {
        // Some actions...
        break;
    }
}

You can get the difference of the Arrays with the PHP function array_diff .

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

Results in

Array
(
    [1] => blue
)

You can use nested loops for this.

for($i=0; $i<count($array1); $i++){
    for($j=0; $j<count($array2); $j++){
        if($array1[$i] == $array2[$j]){
            //some action here
        }
    }
}

kindly correct the errors. im comparing the arrays values to display respectively with their paired one

if((cardnumb1[1]==123456789) && (passcode[1]==1234))

                         else if ((cardnumb1[2]==987654321) && (passcode[2]==4567))

                         else if ((cardnumb1[3]==123789456) && (passcode[3]==7890))

Even if answered I think, just for reference, is good to know that you can make:

$array_1 = array(1,2,3,4,5);
$array_2 = array(2,4,6,8);

foreach (array_intersect($array_1,$array_2) as $match){
    //do something
}

NOTE: may give some problems with associative arrays.

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