1

I have an input box where a user can input a number and then that number will be outputted into an html page. It all works fine except when you enter in the number 0 it doesn't output anything but it needs to say 0. This is a live baseball game scoring plugin I wrote for WordPress so I need "Inning 1" to read "0" if no runs were scored. Here is the gist of my code:

$t1Inning1 = ( $instance['t1Inning1'] ) ? $instance['t1Inning1'] : '-';

<div><?php echo $t1Inning1 ?></div>

<label for="<?php echo $this->get_field_id('t1Inning1'); ?>">
  <input id="<?php echo $this->get_field_id('t1Inning1'); ?>" 
  name="<?php echo $this->get_field_name('t1Inning1'); ?>"
  value="<?php echo esc_attr( $instance['t1Inning1'] ); ?>"
  maxlength="2" size="3" />
</label>

You can see the output at http://juniorregionals.com/ in the middle left. The '-' is just the default value which doesn't change when you input 0 in the plugin and save it but again I need it to read 0 if you input 0.

Let me know if I need to be more specific

1
  • Try ending your <div><?php echo $t1Inning1 ; ?></div> Commented Jul 27, 2014 at 23:25

2 Answers 2

3

You're using the ternary operator on 0 which is a falsy value, e.g.

echo 0 ? 1 : 2; // 2

Perhaps you meant to check if $instance["t1Inning1"] is set rather than falsy?

$t1Inning1 = isset($instance['t1Inning1']) ? $instance['t1Inning1'] : '-';
Sign up to request clarification or add additional context in comments.

7 Comments

That worked. It lets me put in the 0 and it displays the 0. Awesome! I still need the output to have a dash (-) as the value by default. that way the innings that have yet to be played will show a dash (-) as the score. Which is how it looks if I take out the "isset".
@agon024 I assume the value is always supplied then, just with some alternate value? Otherwise you would indeed see a dash.
In the original code: || $t1Inning1 = ( $instance['t1Inning1'] ) ? $instance['t1Inning1'] : '-'; || this '-' gave it a default value of a dash. with the isset in there it is just blank.
isnt this my correct format: $items = isset(condition) ? value_if_condition_true : value_if_condition_false;
Someone has the know the answer. I am running out of time to get this working. Plzzzzz help :)
|
0

Someone from the WordpressStackexchange site had me add an exact comparison:

$t1Inning1 = isset( $instance['t1Inning1'] ) && $instance['t1Inning1'] !== '' ? $instance['t1Inning1'] : '-';

and that works flawlessly. Thanks for all your help @Marty. You actually got the ball rolling fast.

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.