Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array how to check if all array values exist in other array

Tags:

arrays

php

I have arrays like these :

$array1 = [1,2,3]; 

$array2 = [3,2,1]; 
$array3 = [2,1,3]; 
$array4 = [2,1,3]; 
$array5 = [1,1,1]; 
$array6 = [3,3,2]; 
$array7 = [1,2,1];
$array8 = [8,9,2]; 

I want to check how array2 until array8 compare to array1. It should give me expected return like this :

$array2 = [3,2,1]; return 'match'
$array3 = [2,1,3]; return 'match'
$array4 = [2,3,1]; return 'match'
$array5 = [1,1,1]; return 'not match'
$array6 = [3,3,2]; return 'not match'
$array7 = [1,2,1]; return 'not match'
$array8 = [8,9,2]; return 'not match'

I tried to compare it using array_diff() but sometimes the result is not like what I expected, especially if on array2 have two same values.

note : array2 until array8 need to always have all 3 values from array1

like image 247
vesuviuzzz Avatar asked Aug 14 '26 11:08

vesuviuzzz


2 Answers

You just need to sort both arrays before comparing them e.g.

sort($array1);
for ($i = 2; $i <= 8; $i++) {
    sort(${"array$i"});
    echo "array $i: " . ($array1 == ${"array$i"} ? 'match' : 'no match') . "\n";
}

Output:

array 2: match 
array 3: match 
array 4: match 
array 5: no match 
array 6: no match 
array 7: no match 
array 8: no match

Demo on 3v4l.org

like image 82
Nick Avatar answered Aug 17 '26 01:08

Nick


You can use array_unique() and then array_diff() for this task:

$array1 = array_unique($array1);
$array2 = array_unique($array2);
$result = array_diff($array1, $array2);

Description of array_unique():

array_unique ( array $array [, int $sort_flags = SORT_STRING ] ) : array

array_unique — Removes duplicate values from an array

Sorting type flags:

  • SORT_REGULAR - compare items normally (don't change types)
  • SORT_NUMERIC - compare items numerically
  • SORT_STRING - compare items as strings
  • SORT_LOCALE_STRING - compare items as strings, based on the current locale.
like image 34
Aniket Sahrawat Avatar answered Aug 17 '26 02:08

Aniket Sahrawat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!