简体   繁体   中英

PHP Array Search - key => string

I got some trouble with in_array()

$list = array(
    "files/" => "/system/application/files/_index.php",
    "misc/chat/" => "/system/application/misc/chat/_index.php"
);

I have this $_GET['f'] which holds the string files/ .
How can I search through the array for possible matches?

If the string is found in the array, then the file should be included

Thanks for any help :)

It's really simple. All you need to do is check if the array element is set. The language construct that's usually used is isset() (yes, it's that obvious)...

if (isset($list[$_GET['f']])) {
}

There's no need to call a function for this, isset is cleaner and easier to read (IMHO)...

Note that isset is not actually a function. It's a language construct. That has a few implications:

  1. You can't use isset on the return from a function ( isset(foo()) won't work). It will only work on a variable (or a composition of variables such as array accessing or object accessing).

  2. It doesn't have the overhead of a function call, so it's always fast. The overall overhead of a function call is a micro-optimization to worry about, but it's worth mentioning if you're in a tight loop, it can add up.

  3. You can't call isset as a variable function. This won't work:

     $func = 'isset'; $func($var); 

array_key_exists is a function that returns true of the supplied key is in the array.

if(array_key_exists( $_GET['f'], $list )) {
    echo $list[$_GET['f']];
}

You can use in_array() in conjunction with array_keys() :

if (in_array($_GET['f'], array_keys($list))) {
  // it's in the array
}

array_keys() returns an array of the keys from its input array. Using $list as input, it would produce:

array("files/", "misc/chat/");

Then you use in_array() to search the output from array_keys() .

Use array_key_exists .

if(array_key_exists($_GET['f'], $list)){
  // Do something with $list[$_GET['f']];
}

in_array() searches array for key using loose comparison unless strict is set. it's like below.

foreach ($array as $value){
    if ($key == $value){
        return true;
    }
}

My way.

function include_in_array($key, $array)
{
    foreach($array as $value){
        if ( strpos($value, $key) !== false ){
            return false;
        }
    }
}

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