-1

Okay, I know this might seem a little off but I am trying to achieve a solution where an image URL is used only when the image URL is valid and exists.

$imglink = URL . 'public/uploads/profile/' . $value['image'];  //valid to be used if image exists
$defaultLink = URL . 'public/images/profile-img.jpg';   // To be used if $imglink is not available

What I have tried is:

$loki = $imglink ? $imglink : $defaultLink;

$imageURL = "<img src='$loki'  width='120px' height='120px' style='border-radius: 50%; border: 2px solid #edf9f3'/>";

ALSO Tried this:

$imageURL = "<img src='<?php echo $imglink ? $imglink : $defaultLink />'  width='120px' height='120px' style='border-radius: 50%; border: 2px solid #edf9f3'/>";

I have tried using different approaches but it isn't working. Also, this is being done in a Codeigniter Controller file.

Badt0men
  • 213
  • 2
  • 11
  • 1
    No, you can not use `if` inside of a _string_. And no, you can not use `` again _inside_ of a string either. You could do this in several steps - assign first part of the string, then do an actual if/else, where you append more to the end of your string variable, and then the rest after; or you can use the _ternary operator_ directly inside a string concatenation statement. – CBroe May 29 '20 at 12:45
  • I might not have clearly stated what isn't working. Well, the statement is not executed within the – Badt0men May 29 '20 at 12:45
  • @CBroe I appreciate the idea, however, can you give me an example with the ternary and string concatenation? – Badt0men May 29 '20 at 12:51
  • Please do a minimum of research on your own. https://stackoverflow.com/questions/14165265/ternary-operator-inside-php-string/14165313, https://stackoverflow.com/questions/1506527/how-do-i-use-the-ternary-operator-in-php-as-a-shorthand-for-if-else – CBroe May 29 '20 at 12:52
  • @Astrildz Your 2nd snippet should work, given `$imglink` and `$defaultLink` actually contain what you think they do. – GrumpyCrouton May 29 '20 at 12:53

1 Answers1

0

You could first check the value in ternary operator and then assign it properly-

// check if $value['image'] is set and not empty; assign value accordingly.
$img = ( !empty($value['image']) ) ? ( URL . 'public/uploads/profile/' . $value['image'] ) : ( URL . 'public/images/profile-img.jpg' );

// give that value in src of img tag
$imageURL = "<img src='" .$img. "'  width='120px' height='120px' style='border-radius: 50%; border: 2px solid #edf9f3'/>";

See if it helps you. :)

sauhardnc
  • 1,961
  • 2
  • 6
  • 16