Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Array Search - key => string

Tags:

arrays

php

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

like image 856
Endre Hovde Avatar asked Mar 01 '26 23:03

Endre Hovde


1 Answers

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);
    
like image 170
ircmaxell Avatar answered Mar 04 '26 13:03

ircmaxell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!