0

I am trying to insert the following if statement into a class but getting the unexpected T_IF error;

class="color_icon_filter '. if ($link_data['id']==$link_data['text']) {$active} .' "

is this not possible or am I doing it wrong?

0

4 Answers 4

2

You shoud open PHP tags to be interpreted server side.

class="color_icon_filter <?php if ($link_data['id']==$link_data['text']) {echo $active} ?>"

EDIT

Or if you're already in PHP tags

echo 'class="color_icon_filter '.($link_data['id']==$link_data['text'] ? $active : '').'"';
Sign up to request clarification or add additional context in comments.

2 Comments

The question says they are getting an unexpected T_IF error. That means the code in the question starts inside a string. You'd need to make additional modifications to the code beyond changing what has been shared already.
an alternative approach is to use the terinary if format... ($link_data['id']==$link_data['text']?$active:"in-active")
0

It is not possible to concatenate an if statement onto a string.

You can do this instead:

$string = "123";
if ($bar) {
   $string .= "456";
}
$string .= "789";

or this:

if ($bar) {
    $baz = "456";
} else {
    $baz = "";
}
$string = "123" . $baz . "789";

You could also use a ternary operator, but your if condition is (relatively) long, so it risks making your code look even more like line noise.

Comments

0

You're trying to concat in an if statement.

I'm assuming there's an echo in front of that line. You can either convert that to sprintf (http://php.net/sprintf) or put the if before the echo line, set the value of $active, and then concat in just the variable.

Personally, I think sprintf/printf is your better solution.

Comments

0

You cannot use an if statement in the middle of an assignment operation, but there are ways to achieve your desired result:

$active = '';
if ( $link_data['id']==$link_data['text'] ) {
    $active = 'active';
}
$class = "color_icon_filter $active";

or a shorter way via the ternary operator:

$active = ( $link_data['id']==$link_data['text'] ) ? 'active' : '';
$class = "color_icon_filter $active";

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.