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?
PRIMARY KEYon the ID column should solve your problem.