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.

Thanks!
Jonathan GreenbergAsked:
Who is Participating?
 
GaryConnect With a Mentor Commented:
Missing closing bracket
$invoice = !empty($_GET['invoice']) ? $_GET['invoice'] : 1;
                                  ^

Open in new window

0
 
Loganathan NatarajanLAMP DeveloperCommented:
try like this,

$get_invoice = $_GET['invoice'];
$invoice = (!empty($get_invoice)) ? $get_invoice : 1;
0
 
Dave BaldwinConnect With a Mentor Fixer 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:
http://php.net/manual/en/language.operators.comparison.php
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
Loganathan NatarajanConnect With a Mentor LAMP DeveloperCommented:
This works fine without warning,

$invoice = (!empty($_GET['invoice'])) ? $_GET['invoice'] : 1;
0
 
Ray PaseurConnect With a Mentor Commented:
The original example had a PHP parse error.  This tests out correctly.
http://www.laprbass.com/RAY_temp_foo.php?invoice=3

<?php // RAY_temp_foo.php
error_reporting(E_ALL);

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

Open in new window

Best to all, ~Ray
0
 
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.

Regards,
Jon
0
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.

All Courses

From novice to tech pro — start learning today.