Compare values of two PHP Codeigniter array

0

I am working with php and codeigniter , and I need to compare two array of type $array1 = ['1','2','3',]. and regardless of the size of both know the values that are not present in both array , for example

$array1 = ['1','2','4','5']
$array2 = ['1','2','6']' 

The result I need

['4','5','6']

    
asked by FeRcHo 25.06.2017 в 21:38
source

1 answer

1

Since this is PHP you can use two functions for this purpose, array_diff to find the difference between arrays (values of the first array passed by parameter that are not in the second array passed by parameter) and array_merge to combine the results.

/* Obtener los valores que están en $array1 y no en $array2*/
$array1 = ['1','2','4','5'];
$array2 = ['1','2','6'];
print_r(array_diff($array1, $array2));  /* Result ['4','5']*/

/* Obtener los valores que están en $array2 y no en $array1*/
$array1 = ['1','2','4','5'];
$array2 = ['1','2','6'];
print_r(array_diff($array2, $array1));  /* Result ['6']*/

Then these two results are combined using the array_merge function, the final result would be:

$result = array_merge(array_diff($array1, $array2), array_diff($array2, $array1));
print_r($result); /*  resultado : ['4','5','6'] */
    
answered by 25.06.2017 / 22:05
source