Search code examples
phpphp-curl

Define an $variable based on a if statement


I have the below PHP code that pulls in a request from a cURL function and I'm left with the following parameters.

$media_url = $entry['media_url'];
$permalink = $entry['permalink'];
$media_type = $entry['media_type'];
$thumbnail_url = $entry['thumbnail_url'];

if (!empty($thumbnail_url)) {
    /* Get the video thumbnail image info */
    $info = getimagesize($thumbnail_url);
    var_dump($info);
} else {
    /* Get the image info */
    $info = getimagesize($media_url);
    var_dump($info);
}

I am using a html div class to define an output on my website and I can't figure out how to target one or the other variable.

<div class="tweet-right" style="width: 100%;">
    <a href="<?= $permalink; ?>" target="_blank"><img class="tw-text instagram-content tw-image" style="width: <?= $width ?>; height: <?= $newHeight ?>;" src="<?= $media_url; ?>" /></a>
</div>

In the above html element, how can I do the following:

If $thumbnail_url is not empty use that as the src=, otherwise use the $media_url as the src=.


Solution

  • You can use the "Elvis operator":

    src="<?= $thumbnail_url ?: $media_url; ?>"
    

    It's just a ternary expression with the middle part omitted. An expression like that will evaluate to the left hand side if it is truthy, otherwise the right hand side.

    If it's possible that either of those variables could be undefined instead of just having empty values, you can use the null coalescing operator instead to prevent undefined variable notices.

    src="<?= $thumbnail_url ?? $media_url ?? ''; ?>"