views:

28

answers:

3

Hi. 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 vanskelighetsgrad 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?

+1  A: 

Can do this:

$car_name = "Rolls-Royce Phantom";
$car_nr = array_search($car_name, $GLOBALS['car_park']);
xil3
A: 

You answered your own:

array_search ()

http://il2.php.net/manual/en/function.array-search.php

Haim Evgi
A: 

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';
}
nikic