4

I'm looking to change the the article a/an in a webpage based on a parameter passed via the URL. So for example, I've got mywebpage.com/?page&qry=dog as the URL, so I would want any a/an articles to be "a" dog (vs "an" aardvark were that the qry). I'm trying to use the code below, however I'm getting a parse error any time I try to load the page.

<?php in_array(substr($_GET['qry'],0,1), array('a','e','i','o','u')) ? 'an' 'a'; ?>

If also tried an IF/ELSE statement, which lead to the same result.

<?php if(in_array(substr($_GET['qry'],0,1), array('a','e','i','o','u'))):'an':'a'; ?>

I'm sure I'm missing something simple, most likely related to my attempt to insert this snippet amongst standard HTML text; can anyone spot my error(s)?

This is the error I get back:

Parse error: parse error in C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\testsite\html\page.html.php on line 117

Thank you!

8
  • <?php if(in_array(substr($_GET['qry'],0,1), array('a','e','i','o','u')))?'an':'a'; ?> try that. Not sure if it will work though. Commented Jun 4, 2015 at 1:59
  • Still getting the same error. Commented Jun 4, 2015 at 2:02
  • what's the exact error? Commented Jun 4, 2015 at 2:05
  • 1
    <?php in_array(substr($_GET['qry'],0,1), array('a','e','i','o','u'))?'an':'a'; ?> removing the if(). Try that. Ternaries don't use if. Commented Jun 4, 2015 at 2:09
  • 1
    Perfect! Also, for anyone who tries to use this in the future, I'd forgotten to echo the statement (which is easily remedied...<?php echo ... If you add the above as an answer I'll be sure to mark it as such. Thank you so much for your help! Commented Jun 4, 2015 at 2:13

2 Answers 2

6
<?php in_array(substr($_GET['qry'],0,1), array('a','e','i','o','u')) ? 'an' : 'a'; ?>

Removing the if(). Ternary operators don't use if(), that's what they're for, to conditionally check all in one go.

Reference:


Footnotes: (OP)

"Perfect! Also, for anyone who tries to use this in the future, I'd forgotten to echo the statement (which is easily remedied...<?php echo ... If you add the above as an answer I'll be sure to mark it as such. Thank you so much for your help!"

Sign up to request clarification or add additional context in comments.

Comments

0

The ternary operator syntax is:

($conditions) ? "if condition is true" : "if condition is false";

In the first example you have a missing : between the possible values. And in the second you have an extra : after condition. Here is the manual and explanation for this operators: http://php.net/manual/en/language.operators.comparison.php (search for ternary operator)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.