Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check existence of an object in array

Tags:

arrays

php

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;
    }
like image 695
Kaan Avatar asked Dec 30 '22 17:12

Kaan


1 Answers

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;
}
like image 60
Andrew Moore Avatar answered Jan 13 '23 12:01

Andrew Moore