Detect empty variable in PHP not working - php

I have been fighting with the following code and variants, but have not been able to come up with anything that works. The idea is that I detect if the variable $largeimg6 (the URL of an image) is empty or not (whether an image has been loaded) and if not, load the value of a default variable ($defaultimage) which holds the URL of a default image..
<?php if(!empty($largeimg6)) : ?>
<img class="rpPicture" id="rpPicture<?php echo $key; ?>" onload="showPicture(this, <?php echo SHOW_PICTURES; ?>)" width="60" height="60" src="<?php echo $largeimg6; ?>" alt="Buy CD!" title="Buy CD!" />
<?php endif; ?>
The problem is that I do not know where to add the arguement for $largeimg6 being empty and therefore adding:
$largeimg6 = $defaultimage
Any help would be appreciated.
Thanks.

You can try this before that if statement:
<?php $largeimg6 = $largeimg6 != '' ? $largeimg6 : $defaultimage; ?>
The != '' comparision may be change according to your need to isset(), strlen(), is_null()(as Ville Rouhiainen suggested) or whatever.

You can use the alternative (and trim as already suggested):
$largeimg6 = trim($largeimg6);
if (isset($largeimg6)&&strlen($largeimg6)>0)
but you'll probably be doing better by filtering the url:
$largeimg6 = trim($largeimg6);
if(filter_var($largeimg6, FILTER_VALIDATE_URL))
More info: http://php.net/manual/es/book.filter.php

Solution
This answer assumes that you have a variable $largeimg6 which is either going to be set to a url or be empty.
That being the case it's a fairly simple fix. You need to remove the if statement entirely and replace your:
<?php echo $largeimg6; ?>
with:
<?php echo (empty($largeimg6)) ? '/default/image.jpg' : $largeimg6; ?>
Explanation
The above is equivalent to:
if(empty($largeimg6)){
echo '/default/image.jpg';
}
else{
echo $largeimg6;
}
But in the form:
(IF) ? THEN : ELSE;

Related

WordPress IF statement isn't outputting ELSE

I have a straightforward if statement to evaluate whether or not an image is set to appear as the logo on a WordPress build. If it returns empty/false, it displays a default image whose location is set as an absolute value.
The problem is when an image ISN'T set, the else statement is failing. I'm not receiving an error, but the code returned is simply an image tag without any source i.e. "< img src >".
Here is the statement:
<?php
$logo = $wp_options['header_logo'];
if(isset($logo) && ($logo !='')) { ?>
<img src="<?php echo $logo['url']; ?>">
<?php } else { ?>
<img src="wp-content/themes/wpdev/images/logo.png">
<?php } ;?>
I guess that if statement is failing, because you are treating $logo variable as a string.
It seems you're using $logo variable as an array, if you want to check out if it is empty you can use is_null() function of PHP.
By the way, we can't understand your problem this way, you should be more specific. Share your error or warning messages, the way it's behaving, etc..
Found a solution to this by specifically referring to the url of the image array when the variable $logo was defined. This way, the IF is evaluating the URL of the image.
The problem seemed to be that the initial IF was being evaluated as TRUE but obviously not returning the URL as this wasn't originally specified in $logo. By looking for the URL in the 'header_logo' array, it corrected the problem.
<?php
$logo = $wp_options['header_logo']['url'];
if(isset($logo) && ($logo !='')) { ?>
<img src="<?php echo $logo; ?>">
<?php } else { ?>
<img src="<!-- Image Location -->">
<?php } ;?>

How to implement PHP inside a image src code?

<img src="socimages/logo/"<?php if ($soca == ""){ echo "logo.jpg"; } else { echo $anotherimage . ".jpg";} ?>>
Basically what I am trying to do is to change the end part of the image src, to pick from a range of specifically named images.
The syntax for the code is obviously not right since I closed the src after /logo/ with the ". But if I do not have the " then my php will not function.
I would suggest, don't mess the logic in your img tag.
<?php
$img = ($soca == "") ? "logo.jpg" : $anotherimage.".jpg";
?>
<img src="socimages/logo/<?php echo $img; ?>" />
Use a ternary, and remember to distinct between "" and '' :
<img src="socimages/logo/<? echo $soca == '' ? 'logo.jpg' : $anotherimage . '.jpg'; ?>">
This will produce a correct <img src="image.jpg"> tag.
A ternary conditional makes the line shorter:
<img src="socimages/logo/<?php echo ($soca=='')?'logo.jpg':$anotherimage.'.jpg';?>">
This is probably shortest:
<img src="socimages/logo/<?php echo ($soca=='')?'logo':$anotherimage;?>.jpg">
Or even this variant, but it depends on the short tags configuration of your site:
<img src="socimages/logo/<?= ($soca=='')?'logo':$anotherimage;?>.jpg">
But all variants are horrible style. You should always try to implement in a transparent manner, easy to read and understand. So instead store the final path inside a variable and echo that into the src attribute of the img tag.

How to put php tag in background url?

I have code like this ;
$Photo = filtering($row['FileIcon128']);
<div class="image" style="background:url(/images/imgs/<?php echo $Photo ?>)"></div>
I tried everything
filtering($row['FileIcon128']); , echo ''.$Photo.'';
instead of
$Photo
But i cant get picture. Any idea?
By the way, i have to use
<div class="image"
Give this a shot:
<?php
$Photo = filtering($row['FileIcon128']);
$string = "/images/imgs/" . $Photo;
?>
<div class="image" style="background-image:url('<?php echo $string; ?>')"></div>
Explanation
I saw 3 possible bugs in your code, which were:
1) <?php echo $Photo ?> without a semicolon after $Photo. I don't know if that's a syntax error or not in inline php, however I added the semicolon to make sure and concatenated the static string with the dynamic variable to make for a less messy inline PHP like this: <?php echo $string; ?>.
2) background:url() is not the right way to do this. You want to be as explicit as you can, so background-image:url().
3) background-image:url() without '' (apostrophes) surrounding the parameter passed. background-image:url('') fixed that. I just echoed the code in between the two apostrophes.

If the input is empty, how do I display something else with PHP?

My WordPress options panel has a section where the user can paste their logo's URL to show up in the header. If the input is blank, I want the Blog's title to show up instead on my header. The ID of the input is "nl_logo", so I added an if statement in my header.
<?php if ("nl_logo") { ?>
<img src="<?php echo get_option('nl_logo'); ?>">
<?php } else { ?>
<h1><?php bloginfo('name'); ?></h1>
<?php } ?>
The first part of the if statement works. However, anything below else doesn't work when I have no URL saved in my input. So, if the input is empty, how do I display something else with PHP? Or is there a different and better way to do this? For example, creating a function and calling the results to display with a simple line of PHP?
Try this... also try to understand it.
Keeping with the established coding style:
<?php $nlLogo = get_option('nl_logo'); ?>
<?php if (empty($nlLogo)) { ?>
<h1><?php echo(bloginfo('name')); ?></h1>
<?php } else { ?>
<img src="<?php echo($nlLogo); ?>">
<?php } ?>
That should atleast be valid PHP now. I don't know if the functions you are using are correct, but if they are this should work.
Here is a cleaner way to do it...
<?php
$nlLogo = get_option('nl_logo');
if (empty($nlLogo)) {
echo('<h1>'.bloginfo('name').'</h1>');
} else {
echo('<img src="'.$nlLogo.'">');
}
?>
Option three because I'm feeling "teachy" using a ternary. Probably a little long for this to be the best choice, but it is another option.
<?php
$nlLogo = get_option('nl_logo');
echo(empty($nlLogo) ? '<h1>'.bloginfo('name').'</h1>' : '<img src="'.$nlLogo.'">');
?>
Note I switched the if / else because I'm using empty and it just feels cleaner to do it this way instead of using !empty()
<h1><?php bloginfo('name'); ?></h1>
Should be
<h1><?php echo bloginfo('name'); ?></h1>
You could try the empty method to test if a string is empty. In context:
if(!empty($nl_logo)) {
// stuff
} else {
// other stuff
}
This does not make sense:
if ("nl_logo")
You're basically saying if the string exists then proceed, which it does, of course.
It makes more sense to take the input string:
$input = $_POST["postedInput"];
As an example, doesn't really matter as long as you know how you got the value into $input.
Now, you can use the ternary operator to determine whether you want to use the user's input or if you want to use the default title:
$img = $input == "" ? bloginfo($input) : get_option($input);
Depending on what your functions do.. if get_options returns a string then this will work.
Anyway, don't mis PHP and HTML, it will make things complicated and you'll be locked into bad design.
Note:
Make sure to check if the input is actually received, using isset.
You are testing for string "nl_logo" to be true. That returns always true.
try changing your code like this:
<?php
$nl_logo = get_option('nl_logo');
if (!empty($nl_logo)):
?>
<img src="<?php echo $nl_logo; ?>">
<?php else: ?>
<h1><?php bloginfo('name'); ?></h1>
<?php endif; ?>
Don't close the php tags.
Whatever html you need to write, just write it as echo statements within one big php block.
This should fix your problem

Output formatted version of variable if it has a value, blank otherwise

I'm looking to add an if statement to display a title if something is in a variable but not 100% sure how to go about it.
My current coding shows:
<?php echo $quote->getmessage(); ?>
But I would like it to show a title and the content of the message if there is content in the variable. If there is nothing within the variable I don't want to show anything.
IMHO it's better to be as verbose as necessary so that the code is easily readable and can be extended without totally rewriting it:
<?php
$message = $quote->getmessage();
if (!empty($message)) {
echo "Title!";
echo htmlspecialchars($message);
}
?>
Use php's isset function to check if a variable is set, and empty to see if it's empty.
For instance
<?php $a = $quote->getmessage();if (!empty($a)) echo $a; ?>
<?php echo ($quote->getmessage() == "") ? "" : "Title <br />".$quote->getmessage(); ?>
Use a ternary operator:
<?php
$quote_var = $quote->getmessage();
echo ($quote_var != null)?$quote_var:'NOTHING!';
//displays 'NOTHING' if the variable is null
?>
<?php
$mssg = $quote->getmessage();
echo (!empty($mssg))?$mssg:'';
?>
If you want your line to be concise, then I would advise this syntax:
<?php $msg = $quote->getmessage() AND print "<h6>title</h6>$msg"; ?>
The AND has a lower precedence than the assignment (but extra whitespace or braces make that more readable). And the second part only gets executed if the $msg variable receives any content. And print can be used in this exporession context instead of echo.
<?php
if(isset($quote->getmessage())
{
echo "My Title";
}
?>

Categories