user9555022
user9555022

Reputation:

Using ternary for variable assignment

In laravel I have a controller

It gets a bunch of data and saves it like so

        $lastinid = $user->onlineApplications()->create($newInsertData);

If payment_status is successfully, i want invoice to be 1, otherwise i want it to be 0. How do I do this using a ternary operator.

if($lastinid->payment_status == "success"){
      $invoice = 1;
    }

Upvotes: 0

Views: 1252

Answers (3)

u_mulder
u_mulder

Reputation: 54831

Using typecasting hint you can even do:

$invoice = (int)($lastinid->payment_status == "success");

This will work as true value is converted to integer 1 and false to integer 0. Of course, this will work for 1/0 only, for all other numbers use ternary.

Upvotes: 0

user8034901
user8034901

Reputation:

You can read about the Ternary Operator and view an example at https://secure.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

For your case:

$invoice = ($lastinid->payment_status == "success") ? 1 : 0;

Upvotes: 1

Sander
Sander

Reputation: 209

$invoice = $lastinid->payment_status == "success" ? 1 : 0;

Upvotes: 0

Related Questions