0

I have an array that looks like this:

{"permissions":["1","2"]}

I'm trying to check if a given string is in the permissions array with the following function

function hasPermission($permission) {
            return in_array($permission, array_column($this->permissions, 'permissions'));
}

When calling the function giving it the string "1" it return false even though 1 is in the permissions array

Any help would be appreciated

Thanks

EDIT

Here is a var Dump of the converted array

array(1) { 
    ["permissions"]=> 
array(2) {[0]=> string(1) "1" 
          [1]=> string(1) "2" 
        } 
} 
4
  • 1
    Did you convert the JSON String to a PHP Object/Array before running this code Commented Jan 6, 2017 at 11:29
  • 2
    If you did it woild be useful to see a var_dump() of the Object/Array Commented Jan 6, 2017 at 11:29
  • I converted the array with json_deocde() Here is a var Dump of the converted array array(1) { ["permissions"]=> array(2) { [0]=> string(1) "1" [1]=> string(1) "2" } } Commented Jan 6, 2017 at 11:30
  • Better to edit you question with additional info, nobody can read code in a comment Commented Jan 6, 2017 at 11:34

3 Answers 3

1

Try like this...

<?php
$json = '{"permissions":["1","2"]}';
$arr = json_decode($json,true);
print_r($arr);
echo in_array(1,$arr['permissions']); // returns 1 if exists
?>

So your function must be like this....

function hasPermission($permission) {
            return in_array($permission, $this->permissions['permissions']);
}
Sign up to request clarification or add additional context in comments.

1 Comment

That worked! Thank you so much i have spent to much time on trying to figure this out.
0

array_column doesn't support 1D arrays, it returns an empty array if so.

Your $permissions array is 1D, so just use $this->permissions['permission'] to access it.

return in_array($permission, $this->permissions['permissions']);

Example:

$array =  ['permissions' => ['1', '2']];
echo (int)in_array('1', array_column($array, 'permissions')); // 0
echo (int)in_array('1', $array['permissions']); // 1

Comments

0

Try this this will work.

$permission = json_decode('{"permissions":["1","2"]}',true);
echo "<pre>";print_r($permission);
if(is_array($permission)){
 echo "this is an array";
}else{
  echo "Not an array";
}

Thanks

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.