fun with arrays and requirement chains

Recently, I had to figure out if a given set of features contained all of their necessary requirements.

For better or worse, the table was modeled so that the feature table referenced itself so that it could create a parent/child requirement chain. For example:

feature_id requirement_id
2 null
5 2
7 null
11 5

So my problem is to find out if a given set of requested features, make sure that the requirements are also present. This includes any requirements the requirement feature may have. In this example, 11 requires 5 which requires 2.
Let’s take $featureRequest1=array(2,5,7,11) and $featureRequest2=array(7,5,11). If I were to run a look up of requirements, I would find that we have

$requirements=array(2,5).

I tried to use the php in_array function but it didn’t work as I expected it to.

in_array($requirements,$featureRequest1); // i expect true
var_dump(in_array($requirements,$featureRequest1)); // false
in_array($requirements,$featureRequest2); // i expect false
var_dump(in_array($requirements,$featureRequest2)); // false

I then realized what I need is for there to be a clear intersection between the requirements and the request.

$requirements==array_intersect($requirements,$featureRequest1); // expect true
var_dump($requirements==array_intersect($requirements,$featureRequest1)); // true
$requirements==array_intersect($requirements,$featureRequest2); // expect false
var_dump($requirements==array_intersect($requirements,$featureRequest2)); // false

I should probably note that array_interest will preserve the array keys. To fix it, you can either flip the 2 arguments or pass the return array to array_values

2 comments on “fun with arrays and requirement chainsAdd yours →

Leave a Reply