0

I am new to PHP, and combining that language with HTML is more confusing. I am sure there is a simple solution to it but with all the answers out there I still unable to make it work for me.

Here is the piece of code. I have an if statement that checks for x_filter, if its true it saves its value in $var.

My problem: I need to rend the value of that $var, once the next if statement, which looks for x_detail, is true. The code as is will not render anything, and also not give any errors and I can't understand why? Any input is much appreciated.

<?php if ($strName == 'x_filter'): ?>
  <?php $var = $this->{$strName}; ?>
  <?php echo $var; ?>
  <!--The echo statement produces the correct value here -->
<?php endif; ?>
<?php if ($strName == "x_detail"):  ?>
  <span class="filter_value">Value of variable should be here: <?= $var; ?></span>
<?php endif; ?>
felixo
  • 1,453
  • 6
  • 33
  • 60
  • 3
    It will be undefined if the first condition is not met. – Qirel Jan 24 '20 at 09:22
  • 1
    You also don't need to jump in and out of PHP like that. The first 6 lines could be within a single ` – Qirel Jan 24 '20 at 09:22
  • 1
    _“and also not give any errors”_ - go and enable proper PHP error reporting first of all then! – 04FS Jan 24 '20 at 09:26
  • 1
    Your problem is not specific to PHP, it will happen in any language: the variable `$strName` cannot be at the same time `'x_filter'` and `"x_detail"`. If the first, the value is defined and not displayed, if the second, it's displayed but not defined. – Kaddath Jan 24 '20 at 09:26
  • The alternative `if`/`elseif` syntax is valid, and preferable to some, I don't find that much of an issue - what I don't understand, and loathe, is the constant in/out of PHP for every line like that. @Kaddath – Qirel Jan 24 '20 at 10:01
  • @Qirel yep, my comment was mostly about the in/out formatting, the part about the `endif` (not `elseif` which is actually very useful) was just an addition. They seem to completely avoid the `{}` syntax in Worpress and use `endif/endwhile` everywhere – Kaddath Jan 24 '20 at 10:05

1 Answers1

0

it's just because when your first condition doesn't met your variable $var remains undefined.

Fazal Mabood
  • 51
  • 2
  • 8