简体   繁体   中英

in_array and isset give different results?

I've got this json file, for instance, where i have some table metadata for my user.

{
    "id": {
        "index": ["primary", "auto_increment"],
        "unsigned": true,
        "type": "integer"
    },
    "nick": {
        "index": ["unique"],
        "type": "varchar",
        "minLength": 4,
        "maxLength": 10
    },
    "pw": {
        "type": "varchar",
        "minLength": 4,
        "maxLength": 10
    }
}

i check if a field is an index and what type of index it is.


if i do the check this way within a foreach

if (isset($value["index"]) && (in_array("primary", $value["index"]) || in_array("unique", $value["index"]))) {
    $arr[] = $key;
}

i get this result, as expected

Array
    (
        [0] => id
        [1] => nick
    )

but if i do it this way within a foreach

if (in_array("index", $value) && (in_array("primary", $value["index"]) || in_array("unique", $value["index"]))) {
    $arr[] = $key;
}

i get this result...

Array
    (
        [0] => id
    )

this is a little bit creepy. does anyone know why? i don't get it. in my opinion the *in_array-sample* must do the same as the isset-sample

in_array does not check keys, it checks values. The isset method works fine and is fast, or you could

if (array_key_exists("index", $value) && (in_array("primary", $value["index"]) || in_array("unique", $value["index"]))) {
    $arr[] = $key;
}
in_array("index", $value)

in_array has a third parameter for checking also types, and to not do loose comparisons. And as your second array has the entry "unsigned": true and "index" == true is true.

Use:

in_array("index", $value, true);

and you won't see any result. Because there's no value which is "index" .

So, use array_key_exists or the isset check, but not in_array which only checks for values.

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