anvd
anvd

Reputation: 4047

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_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");

Upvotes: 4

Views: 4630

Answers (4)

Phil
Phil

Reputation: 164760

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;
    }
}

Upvotes: 4

Kristoffer la Cour
Kristoffer la Cour

Reputation: 2576

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
}

Upvotes: 1

Eric Yang
Eric Yang

Reputation: 1889

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;
    }
}

Upvotes: 1

Scott C Wilson
Scott C Wilson

Reputation: 20016

Do you mean something like

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

... etc for name_mes, name_dou

Upvotes: 2

Related Questions