php - Check if two pairs of values and keys exist in multidimensional

985
$permissions = array(    
    0 => array(  
        "action"   => "CREATE",  
        "subject"  => "USER"  
    ),  
    1 => array(  
        "action"   => "EDIT",  
        "subject"  => "USER"  
    ),   
    2 => array(  
        "action" =>  "DELETE",  
        "subject" => "USER"  
    ),
    3 => array(  
        "action"   => "CREATE",  
        "subject"  => "TASK"  
    ),  
);

I have this code to check if a combination between "key" and "value" there. Works perfectly.

    public static function verifyPermissions($array, $key, $val) {
    foreach ($array as $item){
        if ( $item[$key] == $val)
            return true;
    }
    return false;
}

The following line of code returns "TRUE", but there is no combination "action = EDIT" and "subject = TASK" in the same row of the array.

if(Group::verifyPermissions($permissions,"action","EDIT") && Group::verifyPermissions($permissions,"subject","TASK"))

I need to check these two options simultaneously, in the same row of the array. How do I fix this error?

572

Answer

Solution:

You can expand your function like this

public static function verifyTwoPermissions($array, $keys, $values) {
    foreach ($array as $item){
        if ($item[$keys[0]] == $values[0] && $item[$keys[1]] == $values[1])
            return true;
    }
    return false;
}

// verifyTwoPermissions($permissions, array("action", "subject"), array("EDIT", "TASK"))

People are also looking for solutions to the problem: How to edit php.ini values using PHP functions?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.