如何将变量作为键?

时间:2011-07-23 13:53:19

标签: php arrays explode

如何将变量变为键或值,以便我可以在in_array()中使用它?

例如,

// set the variable
$cnt_firstname = trim($_POST['cnt_firstname']);
$required = trim($_POST['required']);

// set the array for required fields
$array_required = explode(' ',$required);

// check the item is not empty and if it is in the array of required
if(empty($cnt_firstname) && in_array($cnt_firstname, $array_required))
{
$error = true;
echo '<error elementid="cnt_firstname" message="Please enter your fist name." />';
}

这是我将从表单发送的帖子数据

Array
(
    [cnt_firstname] =>
    [cnt_lastname] => 
    [cnt_organisation] => 
    [cnt_email1] => 
    [cnt_telephpne] => 
    [required] => cnt_firstname cnt_lastname cnt_email1
)

我无法得到结果。如果字段为空且该字段位于必需的数组中,我希望它返回false。

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:1)

快速&amp;脏:

if(empty($cnt_firstname) && in_array('cnt_firstname', $array_required))

你编写它的方式不起作用,因为它只会检查,如果$ cnt_firstname在所需数组中,如果它是空的 - 换句话说:是数组中的空字符串吗?

相关问题