user2898075
user2898075

Reputation: 79

Compare the data of two arrays using foreach PHP

I'm currently trying to compare the data of two arrays against eachother. My code looks something like the one below:

foreach ($arrayOne as $one) {
    $variable = $one['one'];
    foreach ($arrayTwo as $two) {
        if ($two == $variable) { 
            echo "Match!";
        }
    }
}

However, it only compares against the first element in $arrayTwo, it's not looping through everything $arrayTwo. Why is this? Furthermore, is there a MORE EFFICIENT way to accomplish what I'm trying to do?

SNIPPET of Array One:

array (
  0 => 
  array (
    'paper_item_id' => 1,
    'type' => 1,
    'cost' => 20,
    'is_member' => false,
    'label' => 'Blue',
    'prompt' => 'Blue',
    'layer' => 1500,
  ),
  1 => 
  array (
    'paper_item_id' => 2,
    'type' => 1,
    'cost' => 20,
    'is_member' => false,
    'label' => 'Green',
    'prompt' => 'Green',
    'layer' => 1500,
  ),
  2 => 
  array (
    'paper_item_id' => 3,
    'type' => 1,
    'cost' => 20,
    'is_member' => false,
    'label' => 'Pink',
    'prompt' => 'Pink',
    'layer' => 1500,
  ),
  3 => 
  array (
    'paper_item_id' => 4,
    'type' => 1,
    'cost' => 20,
    'is_member' => false,
    'label' => 'Black',
    'prompt' => 'Black',
    'layer' => 1500,
  ),
)

SNIPPET of Array Two:

array (
  0 => 'Blue',
  1 => '
Purple Bat Wings',
  2 => '
Black Motorbike',
  3 => '
Test Scarf',
  4 => '
Black',
  5 => '
Green',
  6 => '
Referee Jersey',
  7 => '
Stethoscope',
  8 => '
Custom Hoodie',
  9 => '
',
)

Upvotes: 1

Views: 9620

Answers (2)

Barmar
Barmar

Reputation: 781088

A more efficient way would be to make an associative array from the $arrayOne values:

$check = array();
foreach ($arrayOne as $one) {
    $check[$one['one']] = true;
}
foreach ($arrayTwo as $two) {
    if (isset($check[$two])) {
        echo 'Match! <br/>';
    }
}

DEMO

The actual problem in the original code is that the explode() code is returning an array where each element in $arrayTwo begins with a newline, except the first one. But the corresponding values in $arrayOne don't have newlines, so they don't match. You need to fix the explode() code, which isn't shown in the question.

Upvotes: 1

Jite
Jite

Reputation: 5847

The array_diff (or array_diff_assoc in your case) function returns the values that differs in two (or more) arrays. If return value is empty, they don't differ at all.

Upvotes: 1

Related Questions