1

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?

2
  • You are use stClass (Object) type. Firstly convert to array. Commented Apr 24, 2014 at 23:08
  • its an array of objects Commented Apr 24, 2014 at 23:10

4 Answers 4

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

0

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));

Comments

0

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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.