Jump to content

Check if array is subset of another


ecopetition

Recommended Posts

Hi, I've checked the PHP manual and Googled this but can't find anything that assists me.

 

Does anybody know if there exists a function issubset($childarray, $parentarray) that returns true if $childarray is a subset of $parentarray?  That is, if all the elements in $childarray are included in $parentarray.

 

Many thanks

Link to comment
https://forums.phpfreaks.com/topic/256503-check-if-array-is-subset-of-another/
Share on other sites

Thanks for your reply thorpe, but this function returns the difference in the arrays, how would one use that to see if it's a subarray of the parent array?

 

I read the notes for the function and didn't get anything similar to what I want, also Googled and it seems to have very few results for "subarray".

 

Thanks again.

Perhaps write your own???

<?PHP
function issubset($childarray, $parentarray);
$c = count($childarray);
$valid = 1;
for($i=0;$i<$c;$i++) {
	if(!in_array($childarray[$i], $parentarray)) {
		$valid = 0;
		return $valid;
	}
}
return $valid;
}
?>

Or an array_diff and a few count statements -

 

<?php

$main = range(10,20);

$subarray = array(1,12,13);

$diff = array_diff($main,$subarray);

if(count($diff) == count($main) - count($subarray)){
echo "all elements in the subarray were found in the main array";
} else {
echo "not all the elements in the subarray were found in the main array";
}

A quick array_intersect and count should work.

 

<?php
$a1 = array(2,4,6,;
$a2 = array(1,2,3,4,5,6,7,8,9,10);

function issubset($arr1, $arr2){
    return count($a1)==count(array_intersect($a1, $a2));
}

var_dump(issubset($a1, $a2));

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.