Alex
Alex

Reputation: 750

PHP in_array not behaving as expected

here is my function:

function checkArray($color,$file) {
    $color = trim($color);
    $settings = getSettings($file,1);
    if (in_array($color,$settings)) return true;
    else return false;
}

$settings in this context is an array:

Array
(

    [0] => Black
    [1] => Blackpol
    [2] => Blk
    [3] => Blue
    [4] => Bronz
    [5] => Bronze
    [6] => Brz
)

i have this function looping a few times with the $color parameter changing each time. sample values are "Black","Blue", etc. long story short, checkArray() should return false very few times.

however, it is returning false EVERY time and i cannot for the life of me figure out why. i tried case insensitive searches, trim, printing individual outputs and comparing the strings ("Black" vs "Black")...i am not new to php or arrays but i can't figure out why this would possibly return false. help please!

PRINT_R of $settings (right before the if statement)

  Array
    (
    [0] => Black

    [1] => Blackpol

    [2] => Blk

    [3] => Blue

    [4] => Bronz

    [5] => Bronze

    [6] => Brz

    [7] => Bz

    [8] => Cherry

    [9] => Gold

    [10] => Gun

    [11] => Gunmet

    [12] => Gunmetal

    [13] => Pol

    [14] => Poly

    [15] => Quentin

    [16] => Rootbeer

    [17] => Vis
    )

VAR DUMP OF $color (right before if statement)

string(5) "Black"

Upvotes: 2

Views: 1626

Answers (4)

Jürgen Thelen
Jürgen Thelen

Reputation: 12727

There you go, you got trailing blanks in the strings. Remove them and you're be fine.

Upvotes: 2

magma
magma

Reputation: 8520

Make sure that you are not mixing encodings.

This could be a solution:

in_array( mb_strtolower($color, "UTF-8"), $settings)

Upvotes: 0

mario
mario

Reputation: 145482

Well, the print_r output suggests that each line contains an extra \n linebreak at the end. The use of $file also indiciates that you read it from a file. If so, you just need to trim the input.

You can either adapt getSettings to read it in using:

file($file, FILE_IGNORE_NEW_LINES)

Or post-process it in your color test function:

$settings = array_map("trim", $settings);

Upvotes: 1

Halcyon
Halcyon

Reputation: 57709

Could it be that there are newline characters behind the values in the settings array?

Check your getSettings function, make sure you trim the values there as well.

Upvotes: 1

Related Questions