Jump to content

Archived

This topic is now archived and is closed to further replies.

dfowler

[SOLVED] Compare arrays

Recommended Posts

Hey guys, I have a little problem that I can't seem to figure out.  It's been a long week and I'm a little burned on code; so I'm hoping some fresh eyes can help me.  I have two arrays that I need to compare and pull out the different values from one.  For example:

<?php
$item1 = array('one'=>1,'two'=>2,'three'=>3,'four'=>4,'five'=>5);
$item2 = array('one'=>1,'two'=>2,'three'=>5,'four'=>7,'five'=>5);
?>

Here are two different arrays.  However, they have some fields that are named the same.  I need to compare them and pull out the different values in $item1.  Here is what I tried, but it didn't work:

<?php
$item1 = array('a'=>0, 'one'=>1, 'two'=>2, 'three'=>3, 'four'=>4, 'five'=>5, 'test'=>;
$item2 = array('id'=>1, 'one'=>1, 'two'=>2, 'three'=>5, 'four'=>7, 'five'=>5);

$difference = "";

foreach($item1 as $k=>$v) {
  if($item1[$k] == $item2[$k]) {
    continue;
  } else {
    $difference.= $item1[$k];
  }
?>

Anybody know what I did wrong, or have a better idea?

 

Thanks!

Share this post


Link to post
Share on other sites

how about using array_diff? this will take a lot of the work out of it for you. there are a number of variations of it as well, depending on your key and value setups - head over to the php manual and see which one works best for you.

 

EDIT: should point out array_diff_assoc is probably better-suited to the task here.

Share this post


Link to post
Share on other sites

how about using array_diff? this will take a lot of the work out of it for you. there are a number of variations of it as well, depending on your key and value setups - head over to the php manual and see which one works best for you.

 

EDIT: should point out array_diff_assoc is probably better-suited to the task here.

array_diff_assoc is exactly what I need!  Thanks a lot!

Share this post


Link to post
Share on other sites

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.