Reputation: 1745
Hi I have an object array ($perms_found) as follow:
Array
(
[0] => stdClass Object
(
[permissions_id] => 1
)
[1] => stdClass Object
(
[permissions_id] => 2
)
[2] => stdClass Object
(
[permissions_id] => 3
)
)
I want to use in_array to find any of the permissions_id , I have tried this:
var_dump(in_array(1, $perms_found , true));
But I keep getting :
bool(false)
What I am doing wrong please help?
Upvotes: 1
Views: 326
Reputation: 111
Your array is collection of objects and you're checking if an integer is in that array. You should first use array_map function.
$mapped_array = array_map($perms_found, function($item) { return $item->permissions_id });
if (in_array($perm_to_find, $mapped_array)) {
// do something
}
Upvotes: 0
Reputation: 780869
in_array
is looking for 1
in the array, but your array contains objects, not numbers. Use a loop that accesses the object properties:
$found = false;
foreach ($perms_found as $perm) {
if ($perm->permissions_id == 1) {
$found = true;
break;
}
}
Upvotes: 1
Reputation: 27854
in_array()
will check if the element, in this case 1
, exists in the given array.
Aparently you have an array like this:
$perms_found = array(
(object)array('permissions_id' => 1),
(object)array('permissions_id' => 2),
(object)array('permissions_id' => 3)
);
So you have an array with 3 elements, none of them is the numeric 1
, they are all objects. You cannot use in_array()
in this situation.
If you want to check for the permission_id
on those objects, you will have to wrote your own routine.
function is_permission_id_in_set($perm_set, $perm_id)
{
foreach ($perm_set as $perm_obj)
if ($perm_obj->permission_id == $perm_id)
return true;
return false;
}
var_dump(is_permission_id_in_set($perms_found, 1));
Upvotes: 0
Reputation: 188
Firstly convert to array...
function objectToArray($object) {
if (!is_object($object) && !is_array($object)) {
return $object;
}
if (is_object($object)) {
$object = get_object_vars($object);
}
return array_map('objectToArray', $object);
}
Upvotes: 0