Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
You are use stClass (Object) type. Firstly convert to array. –  maverabil Apr 24 at 23:08
    
its an array of objects –  user3150060 Apr 24 at 23:10

4 Answers 4

up vote 1 down vote accepted

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;
    }
}
share|improve this answer

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);
}
share|improve this answer

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));
share|improve this answer

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
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.