简体   繁体   English

从数组中获取键或值以在php中使用

[英]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_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.: OBS:

  1. array_search() will return false if value is not found; 如果找不到值, array_search()将返回false ;否则,返回false
  2. array_search() is case sensitive , so if you have ' Apple ' in the array and search for ' apple ', it'll return false . array_search() 区分大小写 ,因此如果数组中有“ Apple ”并搜索“ apple ”,则它将返回false

You could break out of the foreach when there is a match and echo the string afterwards. 您可以在有匹配项时break foreach ,然后回显字符串。

$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. 您可以翻转$systemrefcode数组,使值成为键,反之亦然。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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