I'm using PHP 5.2.
It would seem that the in_array built-in (and other comparison builtins) use non-strict comparison (==) rather than strict comparison (===).
Is it possible to force the use of strict comparison locally? (e.g. I would like to switch strict comparison on, call in_array and then switch strict comparison off).
I suppose the obverse of this question is, can you overload the == operator? You can do this in C++ (you can overload pretty much anything in C++!)
The method signature of in_array is:
bool in_array ( mixed $needle, array $haystack [, bool $strict] )
and the manual page has the following to say:
"If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack."
Is that what you're after?
08-02-2007, 04:50 PM
Can you give an example of some specific data and what the expected results are vs what you are getting now?
You won't be able to change the operation of any of the PHP built in functions, unless it has a switch/parameter to do so or you write your own function with the checking you need.
Edit: LOL, I see GJay posted while I was typing this. I see this was a case of RTFM to find out how to use the function properly.
I DID RTFM! :rolleyes:
What I'm after is a way of making those comparison methods perform more than just type checking; I want to be able to overload == to make it behave like === (so that in_array will perform an identically-equals check rather than just a would-print-the-same-as check).
I've written a noddy function to do it, just wondered if there was a built-in to do it!
do you have an example of where your function behaves differently to in_array() with strict=true?
Yep, I have created a class which is self-referential; i.e. it contains a protected member variable which can point to NULL or to a reference to the instance that owns it.
public function foo()
$this->m_selfref =& $this;
When I call in_array($inst, $arr, TRUE) where $inst is an instance of my self-referential class (for which foo has been called) and $arr is an array which contains one or more instances of the same class (also for which foo has been called), I get an out-of-memory error, which suggests that in_array is using == to evaluate $inst against each member of $arr.
My alternative method is:
function in_array_identical(Cselfref $inst, array $arr)
$values = array_values($arr);
foreach ($values as $value)
if ($value === $inst)
This seems to work just fine!