Advise on simplifying a PHP statement - php

I am new to PHP and am coding a template file for a Joomla K2 item layout.
I have an 'extra field' $extrafields[15] configured which outputs as "Yes", "No" or "". $extrafields[16] is a text string.
I have this code, which works but would appriciate advice on how to simplify it, as I know it is probably a bit crude!
if (!empty($extrafields[15])):
if ($extrafields[15] == "Yes") {
echo "<span class=sgl-bold>Sponsored by: </span>";
}
if ($extrafields[15] == "Yes"):
if (!empty($extrafields[16])):
echo $extrafields[16];
endif;
echo "<br>";
endif;
endif;

I'd be inclined to do something like this:
if(!empty($extrafields[15]) && !empty($extrafields[16])){
if($extrafields[15] == "Yes"){
echo "<span class=sgl-bold>Sponsored by: </span>";
echo $extrafields[16];
echo "<br>";
} //endif not empty
} //endif yes

You can make your code more concise with just some simple tweaks:
Get rid of redundant if-clauses where possible,
combine if-clause conditions where it makes sense, and
don't use the alternative syntax for your control structures to cut down noise.
The following snippet preserves the same functionality than your original attempt but is imho more understandable.
if (!empty($extrafields[15]) && 'Yes' === $extrafields[15]) {
echo '<span class=sgl-bold>Sponsored by: </span>';
if (!empty($extrafields[16])) {
echo $extrafields[16];
}
echo '<br>';
}
That said, judging from the context, you probably want to go with the solution BigScar posted here.
To make this snippet even more understandable, you should consider working on the data structure (though I assume that this is something forced upon you by Joomla):
instead of a values in a numeric array like $extrafields[16] use speaking variable names like $showSponsor or the likes, and
instead of the string values of 'Yes', 'No' and '' use boolean values true, false and null.
Remember:
There are only two hard things in Computer Science: cache invalidation and naming things.

if (#$extrafields[15] == "Yes") {
echo "<span class=sgl-bold>Sponsored by: </span>";
echo #$extrafields[16];
echo "<br>";
}

Related

PHP If statement for file_exists for image or video content from database to avoid blank space on website when no data is present

Having an issue with a blog webpage I’m trying to create which includes a database. The database contains 3 columns: 'title' 'content' which are both text and 'media' which is a mediumblob for images.
<?php echo "img src='data:image/jpeg;base64,".base64_encode($row['media'])."'>"; ?>
Everything works fine except when I don't include an image (in the data row) and just include a 'title' & 'content' it leaves a blank square on the page where an image should of been.
So firstly any advice towards an if statement (or something like that) that would check if file_exists (for specifically images) and display it, else exclude <img> (to avoid the blank square).
Something like this (which I know is totally wrong, sorry):
<?php
if (file_exists($row['media'])) { echo
"?php echo "img src='data:image/jpeg;base64,".base64_encode($row['media'])."'>"; ?>"
;}
else { echo
"!--?php echo "img src='data:image/jpeg;base64,".base64_encode($row['media'])."'>"; ?>-->"
;}
?>
Ideally with this blog, every entry will contain EITHER an image OR an embedded video via iframe, which I assume is something like this:
<iframe src="?php echo $emeddedLink; ?>"</iframe> (Haven't tried it as yet)
But I don't want a blank <iframe> showing on the website when using an image for the blog entry and vice versa I don't want a blank <img> box when using an embedded video.
Please any help would be greatly appreciated and apologies in advance for what might seem like a very basic question but I’ve been searching and can't seem to find anything really to avoid the blank square when I don't include an image in a data row... Thanks!
Typically you'd have an IF statement within your loop that spits out the list of content from your database. Something like this.
<?php
$sql = '
SELECT
*
FROM
`my_table`
';
$query = mysql_query($sql) OR die(mysql_error());
print '<table>';
print '<tr><td>Title</td><td>Content</td><td>Media</td></tr>';
while ($row = mysql_fetch_assoc($query)) {
print '<tr>';
print '<td>'. $row['title'] .'</td>';
print '<td>'. $row['content'] .'</td>';
print '<td>'
if (
$row['media'] == '' ||
$row['media'] == null ||
empty($row['media']) ||
!$row['media']
) {
print 'No Media Available';
}
else {
print $row['media'];
}
print '</td>';
print '</tr>';
}
print '</table>';
?>
That should get you going if I understand what you want to do. I tried to format the code to be as easy to read for a beginner as possible. The lines that would most closely pertain to your issue above are these lines here:
if (
$row['media'] == '' ||
$row['media'] == null ||
empty($row['media']) ||
!$row['media']
) {
print 'No Media Available';
}
else {
print $row['media'];
}
I put all the contingencies within the if statement because I'm not sure what you have going on in your database. The only thing I think you'll need to change, given the fact that the image is stored as a blob in your database, is instead of printing out the $row['media'] directly, you'd have to parse it and create an image using whatever strategy you see fit for your project.
Using your code above as an example, it would look like this:
if (
$row['media'] == '' ||
$row['media'] == null ||
empty($row['media']) ||
!$row['media']
) {
print 'No Media Available';
}
else {
print '<img src="data:image/jpeg;base64,'. base64_encode($row['media']) .'"/>';
}
Hope this helps!
You can simply add an if statement into the template to check whether the value isn't empty
<?php if(!empty($media)) { ?>
<img src="<?php echo $media ?>">
<?php } ?>

Setting a CSS element class in PHP

I'm trying to modify a bit of PHP code to get it to assign a unique CSS class to the elements it creates as it cycles through its loop. Theoretically, I'm just trying to take a "name" that's echoed to the screen and assign that as a class to a element that's created next... Here's the intitial relevant code loop:
<?php foreach($my_exams as $exam):
if(!$exam->is_taken) continue;?>
<tr><td><?php echo $exam->name;?></td></tr>
<?php endforeach;?>
Simplistcally, I'm trying to get the string that's echoed by $exam->name to be assigned to the class of that <tr> element. Something like
<tr class="<?php echo $exam->name;"><td><?php echo $exam->name;?></td></tr>
Although I'm sure I'm handling the quotes or syntax improperly (at least, anyway, it doesn't end up assigning the class to the <tr>.
It will help if you stop going in and out of PHP so much, it will probably be easier to read this way:
<?php
foreach($my_exams as $exam){
if($exam->is_taken){
echo '<tr class="'.$exam->name.'"><td>'.$exam->name.'</td></tr>';
}
}
If you want to do double quotes, you need to escape them when you want to echo them, but then you can use a variable without concatenating a bunch of strings. (Once you are using objects/arrays it helps to surround each variable with {})
echo "<tr class=\"{$exam->name}\"><td>{$exam->name}</td></tr>";
Reference: http://us2.php.net/manual/en/language.types.string.php#language.types.string.syntax.double
<tr class="<? echo $exam->name ?>"><td><? echo $exam->name ?></td></tr>
Others have answered this pretty much the same way I am about to, but I want to add this to explain the issue. And why this is not a “stupid” question, but more of a bizarre byproduct of the way that some CMS system mix HTML & PHP within their templates. In short: They format the template as nice HTML to make it seem clean & easy for non-coders, but in doing so their mixing of inline-PHP makes PHP coding seem more difficult than it is. Meaning this code:
<?php foreach($my_exams as $exam):
if(!$exam->is_taken) continue;?>
<tr><td><?php echo $exam->name;?></td></tr>
<?php endforeach;?>
Can easily be this:
<?php
foreach($my_exams as $exam) {
if ($exam->is_taken) {
echo '<tr><td>'
. $exam->name
. '</td></tr>'
;
}
}
?>
Which is now easier to parse from a programming standpoint, so you can now do this:
<?php
foreach($my_exams as $exam) {
if ($exam->is_taken) {
echo sprintf('<tr%s><td>', ' class="' . $exam->name . '"')
. $exam->name
. '</td></tr>'
;
}
}
?>
What I did there is use sprintf to place ' class="' . $exam->name . '"' into the ''. The %s means that is a string that should be placed there, and the string is what comes after the comma in the sprintf statement. I find this much easier to code, test & debug. But in general, the key to making PHP coding easier is to just use straight PHP when any logic needs to be placed in the context of HTML.

PHP - if something is equal to something then echo something

I'm quite new to PHP now that I've started working with wordpress.
I'm trying to get something to work by using 'if'
Essentialy what I'm wanting to do is
If the status is equal to Open then return Link
If the status is not equal to Open then return Link
Here's what I think would work:
<?php
if ($status) == (open) {
echo "id=flashing"
}
?>
Obviosuly, I'm assuming this doesn't work but what I'm wanting to do is create a link
Any help?
This is a really basic PHP syntax question; please read some documentation, and look at some examples before asking for help with every piece of code you write.
There is a comprehensive online manual for PHP, with many examples. It is available in multiple translations, in case English is not your first language.
Things you have wrong in your example, with links to relevant pages of the manual:
no semi-colon to end the statement
no quotes around the string open
brackets in the wrong place in the if statement
The text of your question also confuses return and echo, which have very different meanings.
Does this help?
if ($status == 'open') {
echo 'Link';
} else {
echo '<a href="#" >Link</a>';
}
Just use the following code:
<?php
if ($status == 'Open') {
echo 'Link';
}
else {
echo '<a href="#" >Link</a>';
}
?>
<?php
if ($status == 'open')
{
echo 'Link';
}
else
{
echo '<a href="link" >Link</a>';
}
?>
Assuming Open is a string, it can be written like this (alternatively to the other answers):
echo '<a href="#" '.(($status == 'Open') ? 'id="flashing"':'').'>Link</a>';

Display dynamic text based on GET parameters

I'm trying to learn PHP, and I figured I'd make myself a simple exercise of making a site that if someone goes to it, they get "Hello friend!" but if my wife (who is named Dawn) goes to it, she gets a different message.
Unfortunately, it's always showing up as blank and I'm not really sure why.
I know it works for index.html with just text, and I know it works for index.php as long as I have no <?php tag in it (just text works). But when I try to make it actual php, it just fails.
I'd like site/index.php to yield
"Hello friend!"
I'd like site/index.php?who=Bob to
yield "Hello friend!"
I'd like site/index.php?who=Dawn to
yield "Hello Dawn! I love you!"
Here's what I have:
<?php
print 'Hello ';
$who = $_GET("who");
if($who && $who == "Dawn")
print "Dawn! I love you!";
else
print "friend!";
/>
So, what's wrong?
Access to arrays ($_GET is an array), like in Java, uses square brackets:
$who = $_GET['who'];
Also if($who) evaluates to true if $who is non-false, to check it's set you need to use isset:
if(isset($who) && $who == "Dawn")
Last, as noted by #Shivan, the end tag should be ?>, not />.
Multiple issues, should be:
<?php
print 'Hello ';
$who = $_GET["who"];
if(isset($who) && $who == "Dawn") {
print 'Dawn! I love you!';
} else {
print 'friend!';
}
?>
More information:
if possible, use single quotes for faster parsing
it is a good habit to close if else case with brackets
end tag should be a ?>
try this on for size:
<?php
echo 'Hello ';
$who = isset($_GET["who"])?$_GET["who"]:false;
if($who)
echo "Dawn! I love you!";
else
echo "friend!";
?>
This checks to make sure there is a _GET value with key who or else php will throw errors.

Displaying an item depending on user login

This is the situation:
I have a list of items, and one of LI is:
echo '<li>Link</li>';
Now, I want to make an if statement here - if user is logged in, give home.php, else give index.php - but I'm kinda lost in all those "s and 's and .s so I'm asking for your help
This code won't do :/
echo '<li>Link</li>';
Also, I know I could do it with this code, but I want to finally get those dots and stuff
if ($logged == 0)
{
echo '<li>Link</li>';
}
else
{
echo '<li>Link</li>';
}
<?php echo '<li>Link</li>'; ?>
If you are after a short and concise solution try this:
<li>Link</li>
This is called a ternary operator. If $logged evaluates to true it will print 'home.php', otherwise it will print 'index.php'.
Here's an equivalent in standard if-else notation:
<li>Link</li>
You cannot use if's and echo's in echo parameters.
echo '<li>Link</li>';

Categories