Tiit Remmel
Tiit Remmel

Reputation: 230

difference between two strings

$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;

Upvotes: 1

Views: 1729

Answers (3)

Crashspeeder
Crashspeeder

Reputation: 4311

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)));

Upvotes: 3

Aaron W.
Aaron W.

Reputation: 9299

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);

Upvotes: 3

kclair
kclair

Reputation: 2224

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);

Upvotes: 0

Related Questions