CodeIgniter Forums
Be careful when using in_array - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Be careful when using in_array (/showthread.php?tid=8487)



Be careful when using in_array - El Forum - 05-19-2008

[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!


Be careful when using in_array - El Forum - 05-19-2008

[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.


Be careful when using in_array - El Forum - 05-20-2008

[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.


Be careful when using in_array - El Forum - 05-20-2008

[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