1

I want to echo my String but i have encountered some Problems. The error I get is:

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

Code:

for($i = 1; $i <= 31; $i++){   
$Text="<option value='".$i."'<?php if(@$_POST['geb_tag'] == '".$i."') { ?> selected <?php ;}?>>".$i."</option>";
echo $Text;}                                                        
2
  • You can't have php tags in php tags. Commented Mar 25, 2014 at 19:27
  • You lack a semicolon and I don't know if your goal is actually to "print" some PHP code... but I don't think so. Commented Mar 25, 2014 at 19:27

2 Answers 2

6

You have PHP tags mixed in with your attempt at string concatenation. Take you if statement out and put it onto its own statement. Then add that variable to your string:

$Text="<option value='".$i."'<?php if(@$_POST['geb_tag'] == '".$i."') { ?> selected <?php ;}?>>".$i."</option>"

becomes:

$selected = (@$_POST['geb_tag'] == $i) ? ' selected' : '';
$Text="<option value='".$i."'" . $selected .">".$i."</option>";

A couple of things:

  1. Your string is messy. There are better way to add PHP variables to strings to make them more readable.

  2. Don't use @. You should check to see if that variable is set instead.

.

$selected = (isset($_POST['geb_tag']) && $_POST['geb_tag'] == $i) ? ' selected' : '';
$Text= "<option value='{$i}'{$selected}>{$i}</option>";
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much ! I realy love Stackoverfolw ! It works btw.
So much cleaner using a ternary operator (and more legible). +1 John ;-)
1

There are dozens of ways of doing this, so here's one more: printf(). It's an old school method of recomposing strings (separating parts out) that might improve readability.

# a descriptive variable name can improve readability
$posted_value = "";
if( isset( $_POST['geb_tag'] ) ) $posted_value = $_POST['geb_tag'];

for( $i = 0; $i <= 31; $i++ ) {
    printf(
        "<option value='%s'%s>%s</option>",
        $i,
        ($posted_value == $i) ? ' selected' : '',
        $i
    );
}

Idea is that string parts marked with %s will be replaced by appropriate parameters. Nothing wrong with concatenating strings, but it can get messy. printf() has a sprintf() variant that returns everything as a string, in case you wanted to display it later.

Lastly, there are many programmers who dislike the (statement ? '' : '') but when used appropriately, it can help. It basically means if the statement part is true, use this. If it's false, use the other part.

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.