Reputation: 21
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"
}
}
Upvotes: 0
Views: 399
Reputation: 7004
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']);
}
Upvotes: 1
Reputation: 207
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
Upvotes: 0
Reputation: 951
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
Upvotes: 0