4

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");
3
  • What do you mean by "defined strings"? Commented Jun 12, 2011 at 22:28
  • that have a value inserted by user, in my case, is not empty. Only the fields that have values are added to the array. Commented Jun 12, 2011 at 22:30
  • Does "inserted by user" mean "present in the $_POST array?" Commented Jun 12, 2011 at 22:34

4 Answers 4

4

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Of course, !empty() does more than merely checking if a variable is defined.
2

Do you mean something like

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

... etc for name_mes, name_dou

Comments

1

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

Comments

1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.