cliftonbazaar Posted May 6, 2009 Share Posted May 6, 2009 I have the following array $building_array= array("castle", "storage", "barracks", "hospital", "tower", "inn"); and at one stage in the code I need to find out the number of the array of the matching building so I can complete the following line of code - $town_array[0] = $building; For example if the building chosen was hospital then I need to put the number it is in the array (3) into $town_array[0], not the name of the building (which is what $building is). I would like to say that I have attempted this problem but the truth is that I don't know where to start Link to comment https://forums.phpfreaks.com/topic/157071-finding-a-number-in-an-array/ Share on other sites More sharing options...
trq Posted May 6, 2009 Share Posted May 6, 2009 See array_flip. Link to comment https://forums.phpfreaks.com/topic/157071-finding-a-number-in-an-array/#findComment-827388 Share on other sites More sharing options...
Mark Baker Posted May 6, 2009 Share Posted May 6, 2009 $building = "barracks"; $building_array = array("castle", "storage", "barracks", "hospital", "tower", "inn"); $buildingKey = array_search($building,$building_array); if ($buildingKey === false) { echo 'Not Found'; } else { echo $building.' is key '.$buildingKey; } Link to comment https://forums.phpfreaks.com/topic/157071-finding-a-number-in-an-array/#findComment-827402 Share on other sites More sharing options...
erdomester Posted May 6, 2009 Share Posted May 6, 2009 That's exactly the same I wanted to suggest. You can also you array_search with foreach: $building_array= array("castle", "storage", "barracks", "hospital", "tower", "inn"); foreach ($building_array as $b) { if ($b == "hospital") echo array_search($b,$building_array); } Link to comment https://forums.phpfreaks.com/topic/157071-finding-a-number-in-an-array/#findComment-827404 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.