简体   繁体   中英

get key or value from array to use in php

I want to assign values from an array to a simple variable, my code is as follows :

$codeval = $_POST['code']; //can be Apple or Banana or Cat or Dog
$systemrefcode = array("a" => "Apple", "b" => "Banana", "C" => "Cat", "D" => "Dog");

foreach($systemrefcode as $code => $value) {
     if($codeval == $value){ //if Apple exists in array then assign code and use it further
        $codes = $code;//Assign code to codes to use in next step

     }
$selection = 'Your Selection is -'.$codes.'and its good.';
echo $selection;

When I check in console it shows no response. What am I doing wrong?

You can get the key of the wanted value with array_search() :

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;

So, for your code works, you can use like this:

$codeval = $_POST['code'];
$systemrefcode = array("a" => "Apple", "b" => "Banana", "C" => "Cat", "D" => "Dog");

$code = array_search($codeval, $systemrefcode);

$selection = 'Your Selection is - '.$code.' and its good.';
echo $selection;

OBS.:

  1. array_search() will return false if value is not found;
  2. array_search() is case sensitive , so if you have ' Apple ' in the array and search for ' apple ', it'll return false .

You could break out of the foreach when there is a match and echo the string afterwards.

$post = "1-Apple";
$codeval = explode('-', $post)[1];
$systemrefcode = array("a" => "Apple", "b" => "Banana", "C" => "Cat", "D" => "Dog");
$codes = "";

foreach ($systemrefcode as $code => $value) {
    if ($codeval === $value) { //if Apple exists in array then assign code and use it further
        $codes = $code;//Assign code to codes to use in next step
        break;
    }
}

if ($codes !== "") {
    $selection = 'Your Selection is -' . $codes . ' and its good.';
    echo $selection; // Your Selection is -a and its good.
} else {
    echo "codes is empty";
}

You can flip the $systemrefcode array so that the values become keys and vice versa.

$coderefsystem = array_flip($systemrefcode);
$codes = $coderefsystem($codeval);
$selection = 'Your Selection is -'.$codes.'and its good.';
echo $selection;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM