Finding nr of an array value based on a string that exist in the array
I have an array for all the cars in a online game I'm making that look like this:
$GLOBALS['car_park'] = array (
"Toyota iQ3", "Think City", "Lancia Ypsilon", "Smart fourtwo", "Chevrolet Matiz", "Mazda 2", "Peugeot 107", "Nissan Micra", "Mercedes-Benz 310" /* dårlige biler */
, "Lexus IS-F", "BMW M3 CSL", "Volvo C30", "Dodge Challenger RT", "Audi S3", "Omnibus Sunrider" /* bedre biler vanskelighe开发者_运维问答tsgrad i forhold til dårlige biler 2.45x */
, "Chevrolet Camaro SS", "Porsche GT2 RS", "Lotus Elise", "Rolls-Royce Phantom", "BMW 5-series", "DAF SB3000 Berkhof" /* bra biler 4x */
, "Lamborghini Murcielago", "Ascari A10", "McLaren F1", "Pagani Zonda R" /* sinnsyke biler 8x */
);
$car_name = "Rolls-Royce Phantom"
$car_nr = ?
I have a car name, what I need is the nr for the car. Which is 18 ($GLOBALS['car_park'][18]). How du I find that with a function? array_search?
Can do this:
$car_name = "Rolls-Royce Phantom";
$car_nr = array_search($car_name, $GLOBALS['car_park']);
You answered your own:
array_search ()
http://il2.php.net/manual/en/function.array-search.php
If you do this operation very often in your script, think about not using a slow array_search, but a fast lookup operation.
At the beginning of the script flip your car array:
$cars = array_flip(...);
Afterwards search using lookup:
if (isset($cars[CAR_NAME])) {
echo $cars[CAR_NAME];
}
else {
echo 'Car not found';
}
精彩评论