1

Is it possible to concatenate an if statement inside echo in php? How can I attach some condition based html to an html inside an echo? Something like as follow:

<?php
echo '<div class="main">Some html</div>' . if (is_page('my-account')) {
echo '<div class="account_data">Some account related data</div>';
}; . ;
?>
teccraft
  • 75
  • 8
  • 1
    No. You can use a ternary, but otherwise you'll have to end the statement before you go into the if. – aynber Oct 02 '19 at 12:52

2 Answers2

3

It will help to you. Try this.

<?php
$html = '';
$html .= '<div class="main">Some html</div>';
 if (is_page('my-account')) {
    $html .= '<div class="account_data">Some account related data</div>';
 }
echo $html;
Vaibhavi S.
  • 1,083
  • 7
  • 20
  • This is adding the html inside the if statement to the top of the rest of html. I need it to be at the bottom of everything. – teccraft Oct 02 '19 at 13:05
  • @teccraft what do you mean ?? – Vaibhavi S. Oct 02 '19 at 13:07
  • I mean that due to this code, `''` appears on top of `'
    Some html
    '`. I am already getting this result in my existing approach which is not required.
    – teccraft Oct 02 '19 at 13:09
  • describe your expected output. @teccraft – Vaibhavi S. Oct 02 '19 at 13:11
  • I have some existing html like `
    Some html
    ` inside echo. And I want to concatenate `` with it. But as a result, the html which I am concatenating at the end appears on the top of the html to which I am concatenating this.
    – teccraft Oct 02 '19 at 13:19
  • I have resolved my issue. Actually, your solution was working fine. I was outputing `

    ` instead of `
    ` which was the main cause of appearing on top of the other html.
    – teccraft Oct 02 '19 at 13:28
1

You can try with a ternary operator like so

<?php

    printf(
        '<div class="main">Some html</div>%s',
        is_page('my-account') ? '<div class="account_data">Some account related data</div>' : ''
    );

?>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46