Hello, I am kind of a newbie to PHP. How can I include a conditional statement within a variable? EX: $example = "example"; $mainvariable= "This is just an". if ($example){echo $example;} ." code for my problem"; Code (markup): I keep getting the error: Parse error: syntax error, unexpected T_IF Any help or direction would be fantastic! Thanks in advance,
Why you want to add IF/ELSE to a variable ? It's just not possible ! What you want to get by doing this ?
I was trying to write an advanced search feature and wanted to modify the $sql variable depending on which advanced search variables were included in the search.
Doesn't make sense... your if statement is setup wrong though... if ( $example = "example") { Then do this } Else { Do this }
<?php $example = "Big Example"; $mainvariable= "This is just an "; if (isset($example)) { echo $example." code for my problem"; } else { exit(); // exit script if $example is empty } ?> PHP: Merging variables with a string : $merged = $var1."string"; $merged2 = $var1, "string";
I think this is what you mean : 1. $mainvariable is the main variable. 2. If $example is not empty, add the string 'example' to the $mainvariable. 3. Then, complete the $mainvariable with string 'code for my problem' $example = "example"; $mainvariable = "This is just an"; if ($example != '') { $mainvariable .= $example; } $mainvariable .=" code for my problem"; PHP: - ads2help
You want what's called the "ternary operator". $example = 'bird'; $mainvariable = 'Can the animal fly? ' . ($example == 'bird' ? 'Yes' : 'No'); Code (markup): No need for "if" in this context; just follow your test with a question mark and the result you want if the test is true, and then a colon and the result you want if the test is false. To avoid associative ambiguity just put the whole thing inside a set of parentheses.
all above are true but last one is the best $example = 'bird'; $mainvariable = 'Can the animal fly? ' . ($example == 'bird' ? 'Yes' : 'No');//short if and else