Jump to content

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!

Link to comment
https://forums.phpfreaks.com/topic/167308-solved-compare-arrays/
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.

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!

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.