-4

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

rad
  • 1
  • 2
  • 1
    Search "Ternary operator" its a shorthand way of writing an if/else conditional check. – Cups Feb 11 '13 at 14:02
  • See [`empty()`](http://us3.php.net/manual/en/function.empty.php) and [ternary operations](http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary) – Michael Berkowski Feb 11 '13 at 14:02
  • 1
    What does this have to do with "Undefined index"? – kba Feb 11 '13 at 14:04
  • If you're asking what a ternary statement is then its a duplicate http://stackoverflow.com/questions/4681832/what-does-sign-in-this-statement/4681862. If you're asking about undefined indexes it's too localized. – Mike B Feb 11 '13 at 14:08
  • I didnt even know that was Ternary statement. I got unidentified index error, searched for some solution then I found that line. – rad Feb 11 '13 at 14:18

4 Answers4

2

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"];
}
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
2

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'];
}
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
2

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"];
}
Mitch Satchwell
  • 4,770
  • 2
  • 24
  • 31
0

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.

dreamweiver
  • 6,002
  • 2
  • 24
  • 39