Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare 2 different length arrays to eachother

Tags:

php

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?

like image 518
Henkka Avatar asked Dec 16 '22 13:12

Henkka


2 Answers

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;
    }
}
like image 109
Tom Avatar answered Jan 05 '23 13:01

Tom


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
)
like image 34
Znarkus Avatar answered Jan 05 '23 12:01

Znarkus