05-19-2008, 11:52 PM
[eluser]Lone[/eluser]
Came across the following whilst doing some code today - its an unexpected result (from my point of view) from using in_array(). Best explained using some code:
My array:
My code:
This would return the value of 'testname' being found which of course it was not!
After further investigation (and serializing the array) I came to realise the 'req' field is a Boolean set to TRUE (shown as 1 when using print_r()) and as a result in_array just returns TRUE regardless of the value/string even being in the array!
There is a way to fix this problem by using in_array() in 'strict' mode as follows:
However the (major) downside, this will make any integers not match a number in a string (as it must use the === operator instead of ==).
In my opinion this function should default to be 'strict' when checking a boolean value and leaving 'loose' mode on for other values.
Looks like the 'loose' comparison of values got me again!
Came across the following whilst doing some code today - its an unexpected result (from my point of view) from using in_array(). Best explained using some code:
My array:
Code:
Array
(
[req] => 1
[name] => Email Address
[tag] => EMAIL
)
My code:
Code:
if (in_array('testname',$array)) {
echo 'found';
}
This would return the value of 'testname' being found which of course it was not!
After further investigation (and serializing the array) I came to realise the 'req' field is a Boolean set to TRUE (shown as 1 when using print_r()) and as a result in_array just returns TRUE regardless of the value/string even being in the array!
There is a way to fix this problem by using in_array() in 'strict' mode as follows:
Code:
in_array('testname',$array,TRUE);
However the (major) downside, this will make any integers not match a number in a string (as it must use the === operator instead of ==).
In my opinion this function should default to be 'strict' when checking a boolean value and leaving 'loose' mode on for other values.
Looks like the 'loose' comparison of values got me again!