I want to add an object to an array of objects only if it's not already in the array (I don't want clones). My code doesn't work.
$roleCount = 0;
$roles = Array();
foreach ($result as $row) {
// create a new Role
$role = new Role();
$role->setId($row['role_id']);
$role->setName($row['roleName']);
// add $role to $roles only if it's different from those that already are inside $roles array
if (!in_array($role, $roles)) {
print_r($role); // This is for test purposes
$roles[$roleCount] = $role;
$roleCount++;
echo "new role added ";
}
I thought that in_array
loose comparison should have worked, but it doesn't seem to.
I read on the object comparison page that
Two object instances are equal if they have the same attributes and values, and are instances of the same class.
So, why doesn't my code work? It adds the same role more than once, even if its properties are the same of the role already in the array.
Note: print_r($role)
outputs this:
Role Object ( [id:Role:private] => 55 [name:Role:private] => user [description:Role:private] => [services:Role:private] => Array ( ) )
Role Object ( [id:Role:private] => 55 [name:Role:private] => user [description:Role:private] => [services:Role:private] => Array ( ) )
so it seems that objects properties are the same. Am I wrong?
The role's ID is different, therefore not equal.
You may want to keep an array of role names, rather than trying to compare objects.
Simplest solution: Use the role's ID as a key to the array (IDs are unique, right??)
$roles = Array();
foreach ($result as $row) {
// create a new Role
$role = new Role();
$role->setId($row['role_id']);
$role->setName($row['roleName']);
// add $role to $roles only if it's different from those that already are inside $roles array
if (!array_key_exists($role->getId(), $roles)) { //Check if ID already exists as an array key.
$roles[$role->getId()] = $role;
echo "new role added ";
}
I'm assuming Role
has a getId()
method, if not, $row["role_id"]
would work just fine as well.