views:

117

answers:

2

Hi, at first I wanna say that I'm new in PHP.

I have an implementation that checks an object is in array or not, if not adds another array. But it always returns false and adds in theorder array.

How can I solve it?

Here part of the code:

$temp = new tempClass($x, $y);

 if (!in_array($temp, $temp_array)) {
   $temp2_array[] = $temp;
 }
+1  A: 

Since you are adding instances in the array, make sure that the array in_array() uses strict mode comparison:

$temp = new tempClass($x, $y);

if (!in_array($temp, $temp_array, true)) {
  $temp2_array[] = $temp;
}

Also, you need to understand that 2 different instances of a class, even if they hold the same data, are still 2 different instances. You'll need to create your own loop and compare your instances manually if you which to know if 2 instances are the same.

You can omit strict mode which will compare the members of the class, but as soon as you have a different member, it will be non-equal.

$temp = new tempClass($x, $y);

if (!in_array($temp, $temp_array)) {
  $temp2_array[] = $temp;
}
Andrew Moore
As you said I created my own loop but again I get same result. Here is the code: function exists($b, $array) { foreach( $array as $a ) if($a->x == $b->x) return true; return false; }
Kaan
Then I really don't know what to say. Seems to me you are pasting pseudo-code instead of your code, but your problem is in your code. A semi-colon between the if statement and the braces perhaps?
Andrew Moore
A: 

I think it's because you're checking for a reference to the new object in your array, not the values of that object. Try doing:

print_r($temp_array);

And see what you get... this should give you an idea of how to fix it.

Cahlroisse