dfowler Posted July 24, 2009 Share Posted July 24, 2009 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! Quote Link to comment Share on other sites More sharing options...
akitchin Posted July 24, 2009 Share Posted July 24, 2009 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. Quote Link to comment Share on other sites More sharing options...
dfowler Posted July 24, 2009 Author Share Posted July 24, 2009 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! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.