简体   繁体   中英

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"

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

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.

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);

Make sure that you are not mixing encodings.

This could be a solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM