PHP检查后得到数组的结果

I need the result is the name of the fruit. Not it's string name. So I write two arrays for checking then call the fruit name.

Here's my code:

//$fruit_post = $_POST['fruit_avocado'];
$fruit_post = 'fruit_avocado';

$fruit_list = [
    'fruit_apple',
    'fruit_apricot',
    'fruit_avocado',
    'fruit_banana',
    'fruit_blueberry',
    'fruit_boysenberry',
    'fruit_cantaloupe',
];

$fruit_name = [
    'Apple',
    'Apricot',
    'Avocado',
    'Banana',
    'Blueberry',
    'Boysenberry',
    'Cantaloupe',
];

if (in_array($fruit_post, $fruit_list)) {

    $output = array();

    foreach ($fruit_list as $from => $to) {
        $output[$to] = $fruit_name[$from];
    }

    echo $output[$to]; // Result must be "Avocado". Not Cantaloupe.
}

Please help

Thank you!

If you combine the two arrays into one then you could have the $fruit_post as the key and search for it. And then return the value of that array as the fruit name. Very simple.

    $fruit_list = array(
        'fruit_apple' => 'Apple',
        'fruit_apricot' => 'Apricot',
        'fruit_avocado' => 'Avocado'
    );

if(array_key_exists($fruit_post,$fruit_list)) {
     echo "fruit is " . $fruit_list[$fruit_post]; 
}

That would be a much more elegant solution if you ask me.

If you stay with your data structure the simplest solution would be the following

if (in_array($fruit_post, $fruit_list)) {

    echo $fruit_name[array_search($fruit_post, $fruit_list)];
}

With array_search you can retrieve the key of your furi_list array and get the equivalent inside your furit_name array.

But i would suggest to merge your two arrays to a key => value thing:

$fruit_post = 'fruit_avocado';

$fruit_list = [
    'fruit_apple' => 'Apple',
    'fruit_apricot' => 'Apricot',
    'fruit_avocado' => 'Avocado',
    'fruit_banana' => 'Banana',
    'fruit_blueberry' => 'Blueberry',
    'fruit_boysenberry' => 'Boysenberry',
    'fruit_cantaloupe' => 'Cantaloupe',
];

if (in_array($fruit_post, array_keys($fruit_list))) {
    echo $fruit_list[$fruit_post];
}
$mixArray = array_combine($fruit_list, $fruit_name);

echo $mixArray [$fruit_post];