Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP in_array object comparing?

Tags:

php

Can the in_array function compare objects?

For example, I have an array of objects and I want to add them distinctly to another array. Is it possible to check if an object has already been added like so:

in_array($distinct, $object); 

or is there any other way?

like image 518
gorgi93 Avatar asked Jun 21 '13 09:06

gorgi93


People also ask

How can you compare objects in PHP?

PHP has a comparison operator == using which a simple comarison of two objecs variables can be performed. It returns true if both belong to same class and values of corresponding properties are are same.

How do you check if a value exists in an array in PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

Is in_array fast?

in_array will be faster for large numbers of items. "large" being very subjective based on a lot of factors related to the data and your computer.

What is use of in_array function in PHP?

PHP in_array() Function The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.


1 Answers

You can use strict comparison:

in_array($object, $array, TRUE); 

Usage example:

$a = new stdClass(); $a->x = 42;  $b = new stdClass(); $b->y = 42;  $c = new stdClass(); $c->x = 42;  $array = array($a,$b);  echo in_array($a, $array, true); // 1 echo in_array($b, $array, true); // 1 echo in_array($c, $array, true); // 
like image 177
Alain Tiemblo Avatar answered Sep 20 '22 00:09

Alain Tiemblo