Asim Zaidi
Asim Zaidi

Reputation: 28284

how to make this if else in ternary operator

I am looking for email in my view page. there are two ways email can get there. Either by POST or by SESSION. if it is a $_POST then I want to use the $_POST email other wise I want to use the email saved in session. Currently the code I have is below

$email = (isset($_POST['email']) ? $_POST['email'] : '');

whats the BEST way to do it in least lines of code

Upvotes: 0

Views: 82

Answers (3)

Federkun
Federkun

Reputation: 36924

A funny alternative to the correct answer of @Gabriel Santos

$input = function($param, $default = '') {
    static $input;

    if (null === $input) {
        $input = array_merge($_SESSION, $_POST);
    }

    return isset($input[$param]) ? $input[$param] : $default;
};


// get input
$email = $input('asd');

Upvotes: 0

desertwebdesigns
desertwebdesigns

Reputation: 1045

I'm guessing you're just looking for this (assuming the email address is stored in the $_SESSION array under the key email):

$email = (isset($_POST['email']) ? $_POST['email'] : $_SESSION['email']);

Or am I misunderstanding your question?

Upvotes: 3

Gabriel Santos
Gabriel Santos

Reputation: 4974

Try this:

$email = (isset($_POST['email']) ? $_POST['email'] : (isset($_SESSION['email'])) ? $_SESSION['email'] : '');

Which is the same of:

if(isset($_POST['email'])) {
    $email = $_POST['email'];
} else {
    if(isset($_SESSION['email'])) {
        $email = $_SESSION['email'];
    } else {
        $email = '';
    }
}

Upvotes: 0

Related Questions