Shorthand if else not working

Hi guys,

I try to get this code snippet working without success.
What’s wrong with it:

<?php ((empty($_GET['category'])) ? '' : ?>
	<div class=sidebar>
		<a href='category.php'>Category</a>
	</div>
<?php ); ?>

I got this error:

Parse error
: syntax error, unexpected '?> ' in
path_to_sidebar.php
on line
88

Count the brackets on the left and right hand sides. They do not match.

There’s one under the html.

Back on the computer…

Try this:

<?php if (  ! empty($_GET['category'] ) ) : ?>
    <div class=sidebar>
        <a href='category.php'>Category</a>
    </div>
<?php endif; ?>

// Or this:
<?php if (  ! empty($_GET['category'] ) ) { ?>
    <div class=sidebar>
        <a href='category.php'>Category</a>
    </div>
<?php } // endif; ?>



It looks like you’re trying to use the ternary operator for something it simply can’t do. It’s not really a shorthand if-else, although I can see why it might be thought of as such.

It’s not at all clear what your code is meant to do, whereas John’s code is clear that it’s an if clause.

I think of the tenary operator as a quick and dirty if statement.

<?php echo (!empty($_GET['category'])) ? '<div class="sidebar"><a href="category.php">Category</a></div>' : NULL; ?>

though I think this would be better:

<?php echo (isset($_GET['category'])) ? '<div class="sidebar"><a href="category.php">Category</a></div>' : NULL; ?>
is how I would write it.

This works (assuming you’re doing something like an echo or variable assignment that you didn’t show in the example), replacing the “in ↔ out PHP” stuff which IMHO tends to get messy even when it does “work”.

<?php ((empty($_GET['category'])) ? '' : "
	<div class=sidebar>
		<a href='category.php'>Category</a>
	</div>
" ); ?>
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.