Internet Strategy Guide

fun with arrays and requirement chains

by on Dec.01, 2010, under development, php, web dev

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

:,

  • http://phpprotip.com chancegarcia

    password protected because it's a rough draft. will publish to public later.

  • http://kander.myopenid.com/ Sander

    Why is this showing up in the Planet PHP feed if it's not visible yet :/

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!