这是我的代码:
$day = 1;
$dayList = array("0"=>"Sunday","1"=>"Monday");
if(in_array($day,$dayList)) {
echo $dayList[$day];
}
我尝试了$day = 0
,它很好用,但是如果string是1
,那是行不通的。
我该如何解决这个问题?
答案 0 :(得分:0)
in_array()
检查值,而不是键。因此,在这种情况下,它不会做您想要的。 isset()
是您需要使用的功能,请尝试以下操作:
if (isset($dayList[$day])) {
...
}
答案 1 :(得分:0)
使用array_key_exists:
$day = 1;
$dayList = array("0"=>"Sunday","1"=>"Monday");
if(array_key_exists($day,$dayList)) {
echo $dayList[$day];
}
更多信息: http://php.net/manual/en/function.array-key-exists.php
另一种方法: 您可以创建一个返回该值或键的函数,如下所示:
function getDayOfTheWeek($name)
{
$dayList = array("0"=>"Sunday","1"=>"Monday","2"=>"Tuesday","3" => "Wednesday");
// if a string make sure it's capitalized
if (preg_match('/[^A-Za-z]/', $name)) {
$name = ucwords(strtolower($name));
} else {
// if not a string flip the array and get name
$dayList = array_flip($dayList);
}
return $dayList[$name];
}
// print results for each call to function
var_dump(getDayOfTheWeek('0')); // returns Sunday
var_dump(getDayOfTheWeek('1')); // returns Monday
var_dump(getDayOfTheWeek('Monday')); //returns 1
var_dump(getDayOfTheWeek('Tuesday')); // returns 2