1
$first = 1,2,3,4,5;
$second = 1,3,5,6;

I need to get difference of those two, so that result would be like:
$result = 2,4,6;

3 Answers 3

3

Assuming you mean

$first = "1,2,3,4,5";
$second = "1,3,5,6";

then try

$first_array = explode(",", $first);
$second_array = explode(",", $second);
$result_array = array_merge(array_diff($first_array, $second_array), array_diff($second_array, $first_array));
$result = implode("," $result_array);
Sign up to request clarification or add additional context in comments.

Comments

3

try this:

implode(',',array_diff(explode(',',$first),explode(',',$second)));

EDIT:

updated to fully diff (found on PHP.net and modified):

$first = explode(',', $first);
$second = explode(',', $second);
echo implode(',',array_diff(array_merge($first, $second), array_intersect($first, $second)));

3 Comments

array_diff wouldn't return the 6 I don't think
array_diff Compares array1 against array2 and returns the difference - have to merge both ways. check my answer
@AaronW. Thank you for clarifying. I wasn't aware of this. I've modified my answer after seeing another way in the comments for array_diff() on PHP.net
0

first, i'll assume that your strings are properly quoted as strings:

$first = "1,2,3,4,5";
$second = "1,3,5,6";
$diff_string = array_diff(explode(",", $first), explode(",", $second));
$diff_array = implode(",", $diff_string);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.