array_search (http://uk.php.net/manual/en/function.array-search.php) searches an array for a value an returns the corresponding key. What I need to do is search an array for a key and return the corresponding value. Now I know the first thing you may think is that I'm really silly and forgot it's just $foo[bar]. However, the key itself will be variable, and I can't put $foo[$keynumber] as anyone who is familiar with PHP will know that is incorrect. I'm sure it's simple. Can anyone give me a pointer? Thanks .
I'm not an expert at PHP but you can do $keyname = 'whateveristhatkeyname'; echo $foo[$keyname]; PHP:
Unfortunately you can't . I'm thinking perhaps there is a way to switch the keys and values in an array, then I could use array_search. If anyone knows how this can be done that'd be appreciated .
I don't know if its a version thing but I'm using that method successfully now, I've tested it to make doubly sure and it works fine Can you post some sample code that isn't working?
That's exactly how it's done, in fact the whole point of arrays and hashtables is that you can lookup the value using the key, and of course it can be a variable dct's example will work perfectly.
My mistake . I'm sure I'd tried that a while back on a different script and it didn't work - maybe like dct said it's a version thing (or maybe I'm just an idiot ). Thanks!
try $keyname = 'whateveristhatkeyname'; if (isset($foo[$keyname])) echo "I've already added {$keyname}"; Code (markup):