添加到数组if is defined-php


add to array if is defined -php

我有这个代码

$courses = array("name_lic", "name_mes", "name_dou");

如果定义了name_lic, name_mes, name_douc,我如何添加到数组?

例如:如果定义了name_lic,则插入到数组中,如果未定义name_mes或为空,则不插入到数组和name_dou中。

基本上,数组只能有定义为的字符串

在我的例子中应该是:

$courses = array("name_lic");

我猜"由用户插入"意味着由于表单提交而在$_POST中出现的值。

如果是这样,那就试试这个

$courses = array("name_lic", "name_mes", "name_dou");
// Note, changed your initial comma separated string to an actual array
$selectedCourses = array();
foreach ($courses as $course) {
    if (!empty($_POST[$course])) {
        $selectedCourses[] = $course;
    }
}

你的意思是吗

if (isset($name_lic)) { 
    $courses[] = $name_lic;
}

name_mes、name_dou 等

如果值是空字符串,则

isset将返回TRUE,这显然是您不想要的。尝试

if (!empty($_POST['name_lic'])){
    $courses[] = $_POST['name_lic'];
}
// etc

例如,如果要对$_POST:的所有值执行此操作

foreach ($_POST as $key => $value){
    if (!empty($value)){
        $courses[$key] = $value;
    }
}

首先,如果您的代码是:

$courses = array("name_lic, name_mes, name_dou");

那么$courses是一个只有一个键的数组,你应该像这样删除":

$courses = array("name_lic", "name_mes", "name_dou");

现在,如果你想知道数组是否包含一个值为"name_lic"的键,你应该使用函数in_array(),如下所示:

if (in_array("name_lic", $courses)) {
  //Do stuff
}