2

How can I add if function in my PHP code below :

$html = 'blabla
'.if($a = $b).'
{
}
';

When I run that code, it show error like this :

Parse error: syntax error, unexpected 'if' (T_IF) in...

Please help to advice.

Thanks.

4
  • That is not possible when defining a variable. Commented May 15, 2014 at 9:38
  • Is there any way to solve that? Commented May 15, 2014 at 9:38
  • What do you want to do with this? There is likely a much better way Commented May 15, 2014 at 9:39
  • 1
    Why on Earth would you do that? The only reason is to execute user input and that opens you up, if you are a beginner, as it seems you are, to a world of pain. Commented May 15, 2014 at 9:44

3 Answers 3

4

You need to use a ternary operator.

Example:

$html = 'blabla' . ($a == $b ? 'write something' : 'or something else');
Sign up to request clarification or add additional context in comments.

3 Comments

You don't even know what he's trying to do. How can you give an answer?
He's trying to add an if statement in the middle of a string. This is the best way to do it (according to me).
You will need to put parentheses around the ternary statement, otherwise you will not get the expected result. In the above code (without parentheses), 'blabla' . ($a == $b) is seen as the expression (not ($a == $b)), since . (string concatenation) has a higher precedence than ?: (ternary).
1

use append again to string and use == to compare like

$html = 'blabla';
if($a == $b){
$html .='yes';
}

or use ternary operator like @Viktor Svensson answer

1 Comment

Hi.. I need that IF function inside the html variable
0

You probably want to do something like this.

<?php

$html = 'Your order was ';

if ($order->status === 'success') { // I don't know just doing something random
    $html .= ' successful';
} else {
    $html .= ' unsuccessful';
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.