• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 390
  • Last Modified:

How to phrase php if statement as ternary

I'm not even sure I'm saying this correctly, but I want to express the following php if statement as a ternary operator.  I'd be grateful if someone would show me how.

if (!empty($_GET['invoice'])) {
	$invoice = $_GET['invoice'];
else { $invoice = 1; }

Open in new window

I'm inclined to do this

$invoice = !empty($_GET['invoice'] ? $_GET['invoice'] : 1;

Open in new window

But that appears to be wrong.

Jonathan Greenberg
Jonathan Greenberg
4 Solutions
Loganathan NatarajanLAMP DeveloperCommented:
try like this,

$get_invoice = $_GET['invoice'];
$invoice = (!empty($get_invoice)) ? $get_invoice : 1;
Dave BaldwinFixer of ProblemsCommented:
From the example, it looks like you should do this:
$invoice = (!empty($_GET['invoice'] )) ? $_GET['invoice'] : 1;

Open in new window

See Ternary Operator on this page:
Loganathan NatarajanLAMP DeveloperCommented:
This works fine without warning,

$invoice = (!empty($_GET['invoice'])) ? $_GET['invoice'] : 1;
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Missing closing bracket
$invoice = !empty($_GET['invoice']) ? $_GET['invoice'] : 1;

Open in new window

Ray PaseurCommented:
The original example had a PHP parse error.  This tests out correctly.

<?php // RAY_temp_foo.php

$invoice = !empty($_GET['invoice']) ? $_GET['invoice'] : 1;

Open in new window

Best to all, ~Ray
Jonathan GreenbergAuthor Commented:
Thank you logu, Dave, Gary and Ray.  I appreciate all the responses!  It looks like the bottom line is, as Gary pointed out, I neglected to include a closing parenthesis.

And Ray, special thanks to you for pointing me to the php -l command line prompt!  I can see that as being very useful.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now