0

I have this little script with an example:

The two string, where I want to get the different numbers

$first = "|x|67|x|194|x|113|x|6|x|";
$second = "|x|194|x|113|x|6|x|109|x|";

Explode them, to get the pure numbers

$first_array = explode("|x|", $first);
$second_array = explode("|x|", $second);

Get the difference

$result_array = array_merge(array_diff($first_array, $second_array), array_diff($second_array, $first_array));

See the result

$result = implode(",", $result_array);

My question is:

How to get which number is added and which removed from the first string?

user2617730
  • 39
  • 1
  • 6

3 Answers3

0
<?PHP
$first = "|x|67|x|194|x|113|x|6|x|";
$second = "|x|194|x|113|x|6|x|109|x|";

$first_array = explode("|x|", $first);
$second_array = explode("|x|", $second);

$not_in_first_array = array();
$not_in_second_array = array();

foreach( $first_array as $a )
{
    if( ! in_array( $a , $second_array ) )
    {
        $not_in_second_array[] = $a;
    }
}

foreach( $second_array as $a )
{
    if( ! in_array( $a , $first_array ) )
    {
        $not_in_first_array[] = $a;
    }
}

print_r( $not_in_second_array );
print_r( $not_in_first_array );
?>
DJafari
  • 11,418
  • 8
  • 39
  • 61
0

You could try the following:

<?PHP
$first = "|x|67|x|194|x|113|x|6|x|";
$second = "|x|194|x|113|x|6|x|109|x|";

$first_array = explode("|x|", $first);
$second_array = explode("|x|", $second);

// Get all the values
$allValues = array_filter(array_merge($first_array, $second_array));

// All values which ware the same in the first en second array, and will be removed
$removedValues= array_intersect($first_array, $second_array);

// All new values from the second array
$newValues = array_diff($second_array, $first_array);
Bearwulf
  • 353
  • 1
  • 8
0
//Removed from first string
$removed_from_first_string = array_diff($first_array, $result_array);
print_r($removed_from_first_string);

//Added from second string
$added_from_second_string = array_diff($second_array, $removed_from_first_string);
print_r($added_from_second_string);
MaxEcho
  • 13,989
  • 6
  • 76
  • 86