drummer101 Posted March 28, 2008 Share Posted March 28, 2008 <?php $fruit = array( 1 => _('apple'), 2=>('orange'), 3=>('banana'), 4=>('kiwi'), );?> So my array key is being passed from a select box, given the numeric key, how can I search the array and match the key to the value? array_search(3, $fruit) returns "Array" I'm kinda new to php and arrays confuse me =\ Thanks for the help! Link to comment https://forums.phpfreaks.com/topic/98411-array_search/ Share on other sites More sharing options...
MasterACE14 Posted March 28, 2008 Share Posted March 28, 2008 you got a stray underscore in there.... remove that. then read this.... http://au2.php.net/manual/en/function.array-search.php Regards ACE Link to comment https://forums.phpfreaks.com/topic/98411-array_search/#findComment-503624 Share on other sites More sharing options...
drummer101 Posted March 28, 2008 Author Share Posted March 28, 2008 Thanks for the quick response ACE, however I'm looking for a function that does the opposite. Searches the array given a key, and returns the value. array_search — Searches the array for a given value and returns the corresponding key if successful And I don't see any related functions on that page. Regards. Link to comment https://forums.phpfreaks.com/topic/98411-array_search/#findComment-503657 Share on other sites More sharing options...
wildteen88 Posted March 28, 2008 Share Posted March 28, 2008 You'll probably want to use array_key_exists. Link to comment https://forums.phpfreaks.com/topic/98411-array_search/#findComment-503658 Share on other sites More sharing options...
drummer101 Posted March 28, 2008 Author Share Posted March 28, 2008 So there isn't a built in function that checks keys of the array and then returns the attached value to that key? given <?php<?php $fruit = array( 1 => ('apple'), 2=>('orange'), 3=>('banana'), 4=>('kiwi'), );?> I would need to write a function to check if key "4" exists, and return the value if true? Link to comment https://forums.phpfreaks.com/topic/98411-array_search/#findComment-503664 Share on other sites More sharing options...
wildteen88 Posted March 28, 2008 Share Posted March 28, 2008 No but you can do this: $fruit = array( 1 =>('apple'), 2=>('orange'), 3=>('banana'), 4=>('kiwi'), ); $key = 1; if(array_key_exists($key, $fruit)) { echo $fruit[$key]; } // alternative way: if(isset($fruit[$key])) { echo $fruit[$key]; } Link to comment https://forums.phpfreaks.com/topic/98411-array_search/#findComment-503668 Share on other sites More sharing options...
drummer101 Posted March 30, 2008 Author Share Posted March 30, 2008 Hey, awesome, thanks for the example wildteen, as always thanks everyone, got it working like a charm! Also, Mark topic as solved button has gone missing Link to comment https://forums.phpfreaks.com/topic/98411-array_search/#findComment-504505 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.