MichaelP
MichaelP

Reputation: 181

Comparing an array to a multi-dimensional array to find an extra element

I want to do the following.

Assume I have one array.

Array A,

-> [0] = A
-> [1] = B
-> [2] = C

That I want to compare to a multidimensional array

-> [0]
       [0] = 1
       [1] = A
       [2] = B
       [3] = C
-> [1]
       [0] = 2
       [1] = B
       [2] = C
       [3] = A

-> [2]
       [0] = 3
       [1] = C
       [2] = B
       [3] = A

I want to compare the first array, to the content in the multidimensional array. As you can see the multidimensional array has a number attached to each combination of letters. I want to make the comparison in a way that I can get the corresponding number of array A out of array B, assuming that they're in array B too. How can I do this?

Upvotes: 0

Views: 37

Answers (1)

Nathaniel Ford
Nathaniel Ford

Reputation: 21239

This should do it:

public function findSubArray($multiArr, $compArr) {
  foreach ($multiArr as $idx => $arr) { //for each sub array
    $first = array_shift($arr); //take off the first element and store it
    if (count(array_diff($arr, $compArr)) == 0) { //check if the remainder is what you want
      return $first; //if so, return the first element
    }
  } //otherwise loop
}

Upvotes: 2

Related Questions