JasonDavis
JasonDavis

Reputation: 48933

PHP ternary operator not working

The code below takes an array value, if it's key exist it should echo out it's value, the ternary if/else part works but the value is not showing up, can anyone figure out why it won't?

$signup_errors['captcha'] = 'error-class';

echo(array_key_exists('captcha', $signup_errors)) ? $signup_errors['catcha'] : 'false';

Also where I have it echo out false, I do not need an output if a key does not exist, should I just delete the word false or is there something else to make the code only show 1 value?

Upvotes: 1

Views: 958

Answers (4)

Greg Hewgill
Greg Hewgill

Reputation: 992857

I think you've got a parenthesis in the wrong place:

echo(array_key_exists('captcha', $signup_errors) ? $signup_errors['captcha'] : 'false');

Also, check your spelling of 'captcha'.

Upvotes: 6

nobody
nobody

Reputation: 20163

I think you meant:

echo(array_key_exists('captcha', $signup_errors) ? $signup_errors['captcha'] : 'false');

Or if you want no output when the key doesn't exist, use an 'if' statement, not the ternary operator:

if (array_key_exists('captcha', $signup_errors)) { echo $signup_errors['captcha']; }

Upvotes: 2

too much php
too much php

Reputation: 90988

You have misspelled 'captcha' as 'catcha'.

Upvotes: 1

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179109

You have a typo. This:

? $signup_errors['catcha'] :

Should be this:

? $signup_errors['captcha'] :

catcha -> captcha

Upvotes: 3

Related Questions