Jump to content

Finding a number in an array


Recommended Posts

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

$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;
}

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);
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.