NashGC
NashGC

Reputation: 691

Why array_search doesn't work in this case?

Why my in this code array_search doesn't work? I use it without $_POST and all work well. But now I can't understand.

<_php

    $arr = array(
        'Tokyo' => 'Japan',
        'Mexico City' => 'Mexico',
        'New York City' => 'USA',
        'Mumbai' => 'India',
        'Seoul' => 'Korea',
        'Shanghai' => 'China',
        'Lagos' => 'Nigeria',
        'Buenos Aires' => 'Argentina',
        'Cairo' => 'Egypt',
        'London' => 'England');

    ?>


    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        <form method="post" action="exercise.php">
            <select name="city">
                <?php
                    foreach ($arr as $a => $b)
                    {
                        echo "<option>$a</option>";
                    }
                ?>
            </select>

            <input type="submit" value="get a city">

        </form>

        <?php
        if ($_POST)
        {
            $city=$_POST['city'];

            $country=array_search($city, $arr);

            echo "<p>$city is in $country.</p>" ;

        }
        ?>

    </body>
    </html>

I've checked type of $country and it's string, also I've tried use $_POST['city'] instead $country but it still doesn't work. What have I done wrong?

Upvotes: 0

Views: 181

Answers (2)

Stephen Brooks
Stephen Brooks

Reputation: 11

array_search() does not work here, as array_search is searching the values of the array, not the keys.

As you have the key, the best option is, as Alex suggests. However you should also check the key exists first, using array_key_exists(), as you cannot guarantee the value in your $_POST will be one of the ones you are expecting which would cause an E_NOTICE to be thrown if not.

$country = (array_key_exists($city, $arr)) ? $arr[$city] : null; 

array_search(), array_key_exists()

Upvotes: 1

Alex Howansky
Alex Howansky

Reputation: 53563

You don't need array_search(), just use the index value directly:

$city = $_POST['city'];
$country = $arr[$city];
echo "<p>$city is in $country.</p>" ;

Upvotes: 0

Related Questions