I have 2 strings and i'd like to compare the difference and use the values of those items that are different. For example:
$stringA = "1, 2, 3, 4, 5"
$stringB = "1, 2, 4, 5, 6"
So the difference with stringB is that the '3' is missing and '6' is added.
I'd like to perform a function that uses the values '3' and '6'. To put this in context, imagine the strings are used in a MySQL query where I want to update only the records with id 3 and 6 as they have changed so need updating but the rest remain the same so no need to update the database records for those. I hope that makes sense?
How would I get the differences using PHP and ensure the result is again a string with comma separated values? i.e
$stringDifference = "3, 6"
Just ran through the code on my machine, this will solve the trick
$stringA = "1, 2, 3, 4, 5";
$stringB = "1, 2, 4, 5, 6";
$stringA = explode(',', $stringA);
$stringB = explode(',', $stringB);
$Difference_1 = array_diff($stringA, $stringB); // Check string A Against String B
$Difference_2 = array_diff($stringB, $stringA); // Check String B against String A
$Difference = array_merge($Difference_1, $Difference_2); // Merge the two difference arrays together
$Difference = implode(',', $Difference); // Convert to a string
echo "The Difference Between The Two Is: ".$Difference; // Echo the difference
Update
function Differences ($Arg1, $Arg2){
$Arg1 = explode (',', $Arg1);
$Arg2 = explode (',', $Arg2);
$Difference_1 = array_diff($Arg1, $Arg2);
$Difference_2 = array_diff($Arg2, $Arg1);
$Diff = array_merge($Difference_1, $Difference_2);
$Difference = implode(',', $Diff);
return "The Difference Between The Two Is: ".$Difference;
}
$stringA = "1, 2, 3, 4, 5";
$stringB = "1, 2, 4, 5, 6";
// Call By:
echo Differences($stringA, $stringB);
Sorry for the delay with the update. I have been getting used to PHPStorm as a new script editor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With