Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add to array if is defined -php

Tags:

arrays

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_doucare defined?

For example: name_lic is defined then, is insert 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");
like image 318
anvd Avatar asked Feb 24 '23 21:02

anvd


2 Answers

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;
    }
}
like image 53
Phil Avatar answered Mar 01 '23 22:03

Phil


Do you mean something like

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

... etc for name_mes, name_dou

like image 40
Scott C Wilson Avatar answered Mar 01 '23 22:03

Scott C Wilson