简体   繁体   中英

Different result with in_array() and isset()

I have an array $box_activ like this

Array
(
    [0] => categories
    [1] => add_a_quickie
    [2] => last_viewed
    [3] => whats_new
    [4] => wishlist
)

By checking with

in_array('categories', $box_activ)

the result is true .

Why do I get false as result by checking with

isset($box_activ['categories'])

I thought isset() is the more performance method of in_array().

Because one checks if an index/key in the array is set, while the other checks if an equal value is assigned to any of the indexes/keys in the array.

Array
(
    [0] => categories
    [1] => add_a_quickie
    [2] => last_viewed
    [3] => whats_new
    [4] => wishlist
)

0, 1, 2, 3, 4 is the indexes/keys, and categories, add_a_quickie etc is the values each index has.

isset($box_activ[0])
# should then return true.

To traverse the array with key and value:

foreach($array AS $key=>$value)

The array in PHP works pretty much like a hashmap in that strings can be indexes/keys too:

$array['some string'] = 'some value';
echo $array['some string'];
# should print 'some value' to screen.

$box_activ['categories'] gets the element indexed by categories in the array $box_activ . That element does not exist since categories is the value of the element at index 0 .

isset is indeed faster than in_array , but that is in_array has to loop over an entire array, while isset only has to check the variable you passed to it.

isset($box_activ['categories'])返回false,因为categories是一个元素,请尝试isset($box_activ[0])

There is no value in the Array with a key of 'categories'. The key for categories is 0, so to use isset, you would have to get the key for that value..

$key = array_search('categories', $box_activ);

and then

isset($box_activ[$key])

will be true, although there is no need to check that because array_search has already verified that there is a value of categories in the array

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