未定义的索引(PHP)

Need some explanation. I made form as following:

<form action="test4.php" method="post">
    <select name="code">
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
        <option value="D">D</option>
        <option value="E">E</option>
    </select>
    <input type="submit" value="Cus!">
</form>

Then to store value of the form to $code, I used a line of script that I found in a forum

$code= empty ($_POST['code']) ? null : $_POST['code'];

Actually It worked, But it was not explained. Anybody can explain it to me??

It's ternary. The syntax is var = (true) ? trueValue : falseValue; It's the same as this:

if  ( empty($_POST['code']) ) {
    $code =  null;
} else {
    $code = $_POST['code'];
}

empty() returns true if the variable is 0, false, null, empty string, not defined etc.

(condition ? result-if-condition-is-true : result-if-condition-is-false) is called a ternary operator and can be found here in the PHP manual.

It could also be written as this:

if (empty($_POST["code"])) {
    $code = null;
} else {
    $code = $_POST["code"];
}

This is a ternary operator.

Ternary operators take the following form:

condition ? value_if_true : value_if_false

The line in your example is equivalent to the following:

if (empty($_POST["code"])) {
    $code = null;
}
else {
    $code = $_POST["code"];
}

Rad, its a ternary expression. it simply means check the content of $_POST['code'], if true set null else set the value $_POST['code'] to $code .

Rad if you have got your answer, pls tick the check mark against the answer,this would reduce the number of open questions and will be removed from open questions pool.