Asked 8 years ago
14 Oct 2016
Views 7351
Phpworker

Phpworker posted

remove duplicate object from array in php

i have $list which is array of the object with id and other values , i am removing the all object who have id is equal to $id
in short want to remove duplicate object from array $list

$id=10;
foreach($list as $value){
	if($value->id==$id){
		$newlist[$value->id]=$list;
	}
}

is there array_unique like function for the object like object_unique .
above code is working but i want to do it without foreach or any other loop so any how i can shrink code or make performance better
ravi

ravi
answered Nov 30 '-1 00:00

you can do one thing you can skip if condition checking for all element of array . and unset at later stage.



$id=10;
foreach($list as $value){
        $newlist[$value->id]=$list;
}
unset($newlist[$id]);

suppose you have 1000 records . you are not checking every time if there is id match with value 's id so possibly it give some speed to script because we skip one step 1000 times and unset at later stage

Not sure howmuch it save time of script running but you can try it out.
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

array_unique will work to convert object array to unique object array.

$input[] = (object)array("a" => "green", "red", "b" => "green", "blue", "red");
$input []=(object) array("a" => "green", "red", "b" => "green", "blue", "red");
$input []=(object) array("a" => "green", "red", "b" => "green", "blue", "red");

print_r($input);
echo "<br/>";
print_r(array_unique($input));


array_unique cast object to array and it make array unique for multidimensional array and array_unique work for object array as well as it work for array . it give array of unique object
Post Answer