I have an array of subscriptions/plans (access levels):
define('PLAN_A', 0); // 0001 define('PLAN_B', 2); // 0010 define('PLAN_C', 4); // 0100 define('PLAN_D', 8); // 1000 define('PLAN_E', 16); // 10000
A user can be subscribed to one or more plans.
$user_one = array(PLAN_A, PLAN_C); // is subscribed to two plans $user_two = array(PLAN_C); // is only subscribed to one plan
A ‘process’ requires a certain subecription plan level – or multiple plan levels:
$process_1 = array(PLAN_B); // requires only PLAN_B subscripton $process_2 = array(PLAN_B, PLAN_D); // requires either PLAN_B or PLAN_C subscription
I want to check if $user_one
has the ‘authority’ to access $process_1
, and separately check if $user_one
has authority to access $process_2
. And do the same check for $user_two
. (“Authority” is if the user has the subscription plan required by the process.)
It looks like I need to check if any user plan subscription (one or more) is contained in the subscription requirements of the processes.
I tried using bitwise checking (which is why the PLANs have binary values), but that will only work for the check of $process_1
. How do I check if $user_1
has access to $process_2
? Or, how to check if any value of the user array is contained in any value of the process requirement array?
Advertisement
Answer
Since one of the users (jirarium) copies my comment and posts it as an answer, I might as well do it myself and actually get the credit for my piece of code, and not let someone who just copies and pastes other peoples codes claim it as his own.
Here is the function I made yesterday. You input the user & process; It will then iterate through all of the users values (or plans in this case) and check if any one of them is contained in the array of process values you included. Basically check if any value of the user array is contained in any value of the process requirement array, exactly what you wanted.
It will return a true or false that can be used in an if
statement
<?php define('PLAN_A', 1); // 0001 <-- corrected define('PLAN_B', 2); // 0010 define('PLAN_C', 4); // 0100 define('PLAN_D', 8); // 1000 define('PLAN_E', 16); // 10000 define('PLAN_F', 32); // 10000 $user_one = array(PLAN_A, PLAN_C); $user_two = array(PLAN_C); $user_three = array(PLAN_F, PLAN_D); $process_1 = array(PLAN_B); $process_2 = array(PLAN_B, PLAN_D); function check($user, $process){ foreach($user as $pl){ if(in_array($pl, $process)){ return true; } } return false; }
Usage:
if(check($user_one, $process_1)){ echo 'true'; }else{ echo 'false'; }
Live Demo: http://sandbox.onlinephpfunctions.com/code/83d8d135b03d584713738b56db40ecc21e9f4ddd