1

I have a variable $RepCom if it isset, I want it to be the value of the input RepCom.

I'm trying to figure out the right way to make this work...

$x_RepCom = '<input name="RepCom" type="text" value="'. if(isset($RepCom)){echo $RepCom; }.'">';

Just dumping the variable is fine, but I get a Undefined error if it is not set.

 $x_RepCom = '<input name="RepCom" type="text" value="'.$RepCom.'">';

So how do I put the if isset for the $RepCom into the value of the input?

I tryed...

$x_RepCom = '<input name="RepCom" type="text" value="<?php if(isset($RepCom)){echo $RepCom; }?>">';

But that just dumps the string <?php if(isset($RepCom)){echo $RepCom; }?> into the value.

What am I missing?

3 Answers 3

3

You had the right idea, you just had the wrong implementation.

$RepComPrint = (isset($RepCom)) ? $RepCom : '';
$x_RepCom = '<input name="RepCom" type="text" value="'.$RepComPrint .'">';
Sign up to request clarification or add additional context in comments.

2 Comments

you lost me with the ? and : in there. :(
It's called a ternary operator.
2

You would probably want to put the value as an variable:

if(!isset($RepCom))
    $RepCom='';

$x_RepCom = '<input name="RepCom" type="text" value="'.$RepCom.'">';

Now if it is not set, it will be given value of an empty string, which will prevent the undefined error.

2 Comments

what about if I had 50 different variables here? Would I need to do that for each one?
If you ave an array of variable names you can loop through them and check if(!isset(${$varList[$i]})). However, you can set error reporting to a less strict level to avoid the variable undefined warning.
1

Are you a functional programmer? The code you wrote ($x_RepCom = '<input name="RepCom" type="text" value="<?php if(isset($RepCom)){echo $RepCom; }?>">';) reminds me of how it would be implemented in Scheme or Haskell.

The important thing about PHP is that control structures like if it doesn't just return a value; you can't insert it arbitrarily into code.

The way you have to do it in PHP is something like

$x_RepCom = '<input name="RepCom" type="text" value="';
if(isset($RepCom)) { $x_RepCom .= $RepCom; }
$x_RepCom .= '>';

(Written the long way for clarity)

1 Comment

I'm very new to programming & php. That's just my way I guess. Thanks for the tip.

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.