jonas
jonas

Reputation: 5509

comparing two arrays and getting the number of same value

i am trying to compare two arrays using PHP. for example.

$one = ["A", "C", "B", "D", "A", so on....]
$two = ["A", "B", "B", "C", "A", so on....]

What I want to do is to compare the arrays and get the number of items that are the same. I only compare items with the same index. this is what i had in mind

$ctr=0;
if ($one[0] == $two[0]){
    $ctr++;
}

if ($one[1] == $two[1]){
    $ctr++;
}

// so on.......

echo $ctr++;

but the above code is only appropriate for fixed length of array. could anyone one help me with the code?

Upvotes: 1

Views: 221

Answers (3)

Vicky
Vicky

Reputation: 613

Take a look

      $common = array_intersect($one,$two);
      echo count($common);

        // for key 

       $common = array_intersect_key($one,$two);
       echo count($common);

Upvotes: 5

Fallen
Fallen

Reputation: 4565

First, you can use loop instead of writing manually every condition. Demo:

$ctr = 0;
for($i = 0; $i < count($one); $i++) {
    $ctr += $one[$i] == $two[$i];
}

If you want to compare items with same index and length of array may differ, then,

$ctr = 0;
for($i = 0; $i < min(count($one), count($two)); $i ++) {
    $ctr += $one[$i] == $two[$i];
}

In the second piece of code we check till the end of the shorter array.

If you are not interested in order, matching at any place would do, try array_intersect And for additional with index checking Array_intersect_assoc

Upvotes: 4

Amit Merchant
Amit Merchant

Reputation: 51

You can use following to fulfill so:

$arr = array_intersect(array('a', 'b', 'c', 'd'),array('c', 'd', 'e', 'f'));
$array_length = sizeof($arr);

Hope this will help you.

Upvotes: 0

Related Questions