0

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?

1
  • Because the city is the key not the value. Try: $country = $arr[$city]; Commented May 10, 2018 at 17:32

2 Answers 2

1

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()

Sign up to request clarification or add additional context in comments.

Comments

0

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>" ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.