ChrisA ChrisA - 7 months ago 19
PHP Question

ternary operators quotes issue

I'm trying to display a default image in a HTML page in case the original one is not available.

I'm using a ternary operator as the condition is inside an "echo" but I'm having some issues I think with quotes.

The below code doesn't give me an error but instead of displaying the image, it shows the name of the jpg file in text format in the HTML page

<?php
if ($result10->num_rows > 0) {
while($row = $result10->fetch_assoc()) {
echo "<div id='slider-property' class='carousel slide' data-ride='carousel'>
<ol class='carousel-indicators'>
<li data-target='#slider-property' data-slide-to='0' class=''>
" . $row['FotoPrincipale'] . " == '' ? <img src='backup/images/com_jea/images/profile.jpg' alt=''> : <img src='backup/images/com_jea/images/". $row['Main Image'] . "' alt=''>
</li>


Could someone help?

Thank you

Answer

You could try to do the ternary operator outside the echo. It would look like this

<?php
if ($result10->num_rows > 0) {
   while($row = $result10->fetch_assoc()) {
      $src = $row['FotoPrincipale'] == '' ? 'backup/images/com_jea/images/profile.jpg' : 'backup/images/com_jea/images/'. $row['Main Image'];
      echo "<div id='slider-property' class='carousel slide' data-ride='carousel'>
      <ol class='carousel-indicators'>
      <li data-target='#slider-property' data-slide-to='0' class=''>
          <img src='".$src."' alt=''>
      </li>";
   }