Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird in_array() behaviour [duplicate]

Tags:

arrays

php

I have some trouble with the result of in_array(). It is not like I would have expected and as I understand the manual.

Simple test:

$_aOperatorsOneOptin = array('DE-010', 'DE-005');

$bMatchPaymentOperator = in_array(0 , $_aOperatorsOneOptin);

if($bMatchPaymentOperator)
    echo 'found';

I would expect that I would get no result with this, but $bMatchPaymentOperator is true!

I would expect that

$bMatchPaymentOperator = in_array('DE-010' , $_aOperatorsOneOptin);

is true , which it is. But why oh why is the upper statement true?

like image 204
Calamity Jane Avatar asked Jun 09 '26 15:06

Calamity Jane


2 Answers

Use third parameter of in_array to force strict match

<?php

$_aOperatorsOneOptin = array('DE-010', 'DE-005');

$bMatchPaymentOperator = in_array(0 , $_aOperatorsOneOptin, true);

if($bMatchPaymentOperator == true)
    echo 'found';
like image 134
Med Avatar answered Jun 12 '26 06:06

Med


This is because when you compare a number to a string in php, php converts the string to a number before doing the comparison. Strings that don't start with a number get converted to 0, so 0 == 'hello world';

You can force in_array to check the data type as well as the content for an exact match by passing true as the third argument to in_array().

$_aOperatorsOneOptin = array('DE-010', 'DE-005');

$bMatchPaymentOperator = in_array(0, $_aOperatorsOneOptin, true);

if($bMatchPaymentOperator)
    echo 'found';

see http://php.net/manual/en/language.operators.comparison.php for details on comparisons.

like image 44
davey555 Avatar answered Jun 12 '26 08:06

davey555



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!