Jump to content

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));

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.