in_array failed to check array value in php

依然范特西╮ 提交于 2021-02-11 14:47:18

问题


I am making a PHP user permission system where all permission related to specific role are saved in session as like array but when I try to check the it does not true where already the value exists in array.

Here is my session array $_SESSION['userPermissions'] = $userPermissions; here is the var_dump of $_SESSION['userPermissions']

output

You are now logged inarray(6) { [0]=> array(1) { ["permission_name"]=> string(11) "create-role" } [1]=> array(1) { ["permission_name"]=> string(11) "update-role" } [2]=> array(1) { ["permission_name"]=> string(11) "delete-role" } [3]=> array(1) { ["permission_name"]=> string(11) "create-user" } [4]=> array(1) { ["permission_name"]=> string(11) "update-user" } [5]=> array(1) { ["permission_name"]=> string(11) "delete-user" } }

I use bellow function to check array value

 // checks if user can delete an user
  function canDeleteUser() {
    if(in_array('delete-user', $_SESSION['userPermissions'])){
      return true;
    } else {
      return false;
    }
  }

it always return false please help me


回答1:


In order for your code to work you would need to have your userPermissions array to look as follows:

[ 
   'create-role',
   'delete-user',
   ...the rest...
]

while in fact your array look as follows:

[ 
   ['permission_name' => 'create-role'],
   ['permission_name' => 'delete-user'],
   ...the rest...
]

in order to search for a nested value extract first the column:

if(in_array('delete-user', array_column($_SESSION['userPermissions`], 'permission_name'))){

or search by array:

if(in_array(["permission_name"=>"delete-user"], $_SESSION['userPermissions`]))

yet be aware that the second approach is much less secure: as if the array will change (will have other elements) this will fail. I strongly advise to use the first approach.



来源:https://stackoverflow.com/questions/63331794/in-array-failed-to-check-array-value-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!