• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Be careful when using in_array

#1
[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:
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!

#2
[eluser]sikkle[/eluser]
hehehe anything to keep you awake lone Smile

I think it's a good post, thanks for sharing it.

see ya around.

#3
[eluser]Crimp[/eluser]
Whenever I look up any of the PHP array functions, they're always searching for a needle in a haystack.

Do you know how HARD that is?

My advice is to not even bother using these useless functions.

#4
[eluser]xwero[/eluser]
[quote author="Crimp" date="1211285124"]Whenever I look up any of the PHP array functions, they're always searching for a needle in a haystack.

Do you know how HARD that is?

[/quote]
It's not that hard just go in with your hands and if the straw is sticking out your finger you found the needle Smile


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.