From the course: Learning PHP

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Ternary operations

Ternary operations - PHP Tutorial

From the course: Learning PHP

Start my 1-month free trial

Ternary operations

- [Instructor] One common example of using if statements is to make variable assignments based on some condition. Here's what that might look like using our is_logged_in example. We have a variable is_logged_in gets true and then if is_logged_in, we can assign a message to the message variable, message gets Welcome back! Else message gets Hello There! But there's a much more succinct way of doing this with something called ternary operators, which is a shorthand conditional assignment. Let's look at that and then break down the syntax. So we'll write message gets is_logged_in ? Welcome back! Colon Hello There. Let's expand this a little bit so you can see the whole thing on one line. And then if we echo message, and refresh, we have Welcome back! So this single line of code replaces these lines of code. And what we're saying here is message equals or message gets, then we have a condition. So this is replacing the if…

Contents