Home >Backend Development >PHP Tutorial >PHP determines whether an array is a subset of another array_PHP tutorial
Foreword
In the process of completing an algorithm today, there are several required modules, one of which is to determine whether the $a array is a subset of the $b array. Maybe I have written more C recently, so I directly used a for loop to implement it, but it feels like the amount of code Relatively big and not elegant enough! After brainstorming in the QQ group, I found that many system functions provided by PHP can be called. Record them here
Demand
Minimum time complexity to determine whether $a array is a subset of $b array
[php]
// Quickly determine whether $a array is a subset of $b array
$a = array(135,138);
$b = array(135,138,137);
// Quickly determine whether the $a array is a subset of the $b array
$a = array(135,138);
$b = array(135,138,137);
Implementation method
Three methods are introduced here. The ideas are actually the same. The difference lies in the implementation code
for loop traverses
[php]
$flag = 1;
foreach ($a as $va) {
If (in_array($va, $b)) {
Continue;
}else {
$flag = 0;
break;
}
}
if ($flag) {
echo "Yes";
}else {
echo "No";
}
$flag = 1;
foreach ($a as $va) {
If (in_array($va, $b)) {
Continue;
}else {
$flag = 0;
break;
}
}
if ($flag) {
echo "Yes";
}else {
echo "No";
}
Use of array_diff
Code
[php]
$c = array_diff($a, $b);
print_r($c);
$flag = empty($c)?1 : 0;
if ($flag) {
echo "Yes";
}else {
echo "No";
}
$c = array_diff($a, $b);
print_r($c);
$flag = empty($c)?1 : 0;
if ($flag) {
echo "Yes";
}else {
echo "No";
}
Use of array_intersect
Code
[php]
if ($a == array_intersect($a, $b)) {
$flag = 1;
}else {
$flag = 0;
}
if ($flag) {
echo "Yes";
}else {
echo "No";
}
if ($a == array_intersect($a, $b)) {
$flag = 1;
}else {
$flag = 0;
}
if ($flag) {
echo "Yes";
}else {
echo "No";
}
Postscript
A good mentor can not only teach me how to study, but also teach me how to behave and do things, to be grateful and responsible