How to prevent appending same property twice in array in nested foreach

Hey all,

I have two objects that contain object instances. I want to compare the properties of the instances and if the old_parent’s property doesn’t exist as one of the $new_parent’s property, then I place the old_parent’s property in an array called unneeded_ids. Problem is when I use nested foreach to loop through the instances of the two objects, despite old_parent having only one instance with a property id of 1, because it loops twice, the array gets two “1” values rather than just one:

public function update(){
			$vanity_url = new VanityUrl();
			$zones = $this->input->post('zones');
			$zone = new Zone();
			$zone->where_in('name', $zones)->get();
			$subcategory = new Category();
			$old_parents = new Category();
			$old_parents = $subcategory->related_category->get();
			$unneeded_ids = array(); 
				else {
					echo "Error occurred. Please try again.";
			else {
				$new_parents = new Category();
				$controller = $this->input->post('catupload');
				foreach($new_parents as $new){ 
					foreach($old_parents as $old){
						if($new->id != $old->id){
 							array_push($unneeded_ids, $old->id);

The var_dump outputs:

 array(4) { [0]=> int(126) [1]=> int(127) [2]=> int(126) [3]=> int(127) } 

but it should only output:

 array(2) {[0]=> int(126) [1]=> int(127)}

That’s because there’s only one object instance of old_parent that has a property id value of 126 and the same for 127. The nested for each loop is causing it to iterate twice against the same object and sticking it into the array. How do I get desired result?

Thanks for response.

Could you instead make use of the built-in array_merge() and [url=“”]array_unique() functions?

And [fphp]array_diff[/fphp] to find the differences?

That’s right, all depending on his needs.

If he’s only collecting the unneeded ones so that he can loop through them to remove them from another array, using array_merge() on the original two arrays followed by [url=“”]array_unique() means you don’t even need to find the differences.

It all depends on what you ultimately want to achieve.