add to array if is defined -php
i have this code
$courses = array("name_lic", "name_mes", "name_dou");
How i can add to array if name_lic, name_mes, name_douc
are defined?
For example: name_lic
is defined then, is in开发者_JAVA技巧sert in array, name_mes
is not defined or is empty then is not inserted in the array and name_dou
also.
basically the array only can have strings that are defined
in my example should be:
$courses = array("name_lic");
I'm going to guess that "inserted by user" means a value present in $_POST
due to a form submission.
If so, then try something like this
$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;
}
}
Do you mean something like
if (isset($name_lic)) {
$courses[] = $name_lic;
}
... etc for name_mes, name_dou
isset
will return TRUE
if the value is an empty string, which apparently you don't want. Try
if (!empty($_POST['name_lic'])){
$courses[] = $_POST['name_lic'];
}
// etc
For example, if you want to do this for all values of $_POST:
foreach ($_POST as $key => $value){
if (!empty($value)){
$courses[$key] = $value;
}
}
First of all, if your code is:
$courses = array("name_lic, name_mes, name_dou");
then $courses is an array with only one key, you should remove the " " like this:
$courses = array("name_lic", "name_mes", "name_dou");
Now if you want to know if the array contains a key with the value "name_lic" you should use the function in_array() like this:
if (in_array("name_lic", $courses)) {
//Do stuff
}
精彩评论