1

I've an array like

protected $aPermissions = [
    'read' => [
        'show'
    ],
    'update' => [
        'edit',
        'editProfilePicture'
    ]
];

and I want to get the array key for the sub-array ('read', 'update') by a value to possibly find within the sub-array. So searching for 'edit' would return 'update', whereas 'show' would return 'read'.

I tried PHP's array_search function (also recursively, in a loop), but didn't manage to get this to work. What's the best approach to achieve what I want?

2
  • Will the array ever nest deeper? Commented Apr 27, 2019 at 16:09
  • @Andreas in my use case: no. Commented Apr 27, 2019 at 17:06

4 Answers 4

2

One option is using array_filter to loop thru the array and only include sub array that contains the $search string. Use array_keys to extract the keys.

$aPermissions = [
    'read' => [
        'show'
    ],
    'update' => [
        'edit',
        'editProfilePicture'
    ]
];

$search = 'edit';

$result = array_keys(array_filter($aPermissions, function( $o ) use ( $search ) {
    return in_array( $search, $o );
}));

$result will result to:

Array
(
    [0] => update
)
Sign up to request clarification or add additional context in comments.

Comments

1

Assuming that the keys are on the first level and the values are in the second level you could do something like this:

$innerKeys = [
    "show",
    "edit"
];

$output = [];

foreach ($array as $key => $value) {
    if (is_array($value)) {
        foreach ($value as $innerKey => $innerValue) {
            if (isset($innerKeys[$innerKey])) $output[$innerKey] = $key;
        }
    }
}

If your problem is more complex, then you will need to give us additional information.

Comments

1

You can use array_walk and in_array to get the key, there is no return type array it's just simple key name else null

$aPermissions = [
 'read' => [
    'show'
 ],
 'update' => [
    'edit',
    'editProfilePicture'
 ]
];
$searchAction = 'show';
$keyFound = '';
array_walk($aPermissions, function($value, $key) use ($searchAction, &$keyFound){
  in_array($searchAction, $value) ?  ($keyFound = $key) : '';
}); 
echo $keyFound;

Output

read

Comments

0

Look time not used PHP, but this code should work!!

<?php
$a = [
    'read' => [
        'show'
    ],
    'update' => [
        'edit',
        'editProfilePicture'
    ]
];


$tmp = array_keys($a);
$searchterm = 'edit';
for($x =0 ; $x < count($tmp); $x++){
    if(in_array($searchterm,$a[$tmp[$x]])){
        echo $tmp[$x];
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.