PHP determines whether an array is a subset of another array_PHP tutorial

WBOY
Release: 2016-07-14 10:10:30
Original
925 people have browsed it

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477471.htmlTechArticlePreface In the process of completing an algorithm today, there are several requirement modules, among which is judging whether the $a array is A subset of the $b array. Maybe I write C more recently, so I just use a for loop to implement it...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!