I have this code :
<div class="boxContentScroll">
<?
while($row=mysql_fetch_array($query, MYSQL_NUM)) {
?>
<div class="boxAddCategory<? if($row[1]==1) echo "Yes"; else echo "No"; ?>">
<div class="boxAddCategory1">
<? echo $row[0]."<br />"; ?>
</div>
<div class="boxAddCategory2">
<?
if((isset($_SESSION['admin'])) && ($_SESSION['admin']==1)) {
?>
<input type="checkbox" <? if($row[1]==1) echo "checked='checked'" ?> value="categories[]" />
<?
} else echo " "
?>
</div>
</div>
<?
}
?>
</div>
but is not so good read it (just watch the number of ?> or <?). What can you suggest to improve it? Thanks
If you want this code to run on all environments, don't use short_tags (<?). But if you're running this on your own server, you can disregard it.
Use PHP's alternative syntax for control structures. This will make it much more readable.
Don't mix your business logic with your view logic. Either setup your own MVC stack or use a templating engine if you want.
Well I would start with replacing if with short version:
<?php echo ($row[1]==1) ? "Yes" : "No"; ?>
You could write this:
<? if($row[1]==1) echo "Yes"; else echo "No"; ?>
like this:
<?= $row[1] == 1 ? 'Yes' : 'No' ?>
And you could replace this:
if((isset($_SESSION['admin'])) && ($_SESSION['admin']==1)) {
with this:
if ( $admin ) {
and put this before the while loop:
$admin = isset($_SESSION['admin']) && $_SESSION['admin'] == 1;
Any time you're in a loop and have a static condition to check like this:
if((isset($_SESSION['admin'])) && ($_SESSION['admin']==1))
Define it in a variable it outside the loop. If it won't change within the loop, you don't have to check each time, only once. This becomes relevant when doing resource intensive checks and function calls that won't produce a different result outside the loop.
<div class="boxContentScroll">
<?php while($row=mysql_fetch_array($query, MYSQL_NUM)) : ?>
<div class="boxAddCategory <?=($row[1] == 1 ? 'Yes' : 'No')?>">
<div class="boxAddCategory1">
<?=$row[0].'<br />'?>
</div>
<div class="boxAddCategory2">
<?php if((isset($_SESSION['admin'])) && ($_SESSION['admin']==1)) : ?>
<input type="checkbox" <?=($row[1]==1 ? 'checked="checked"' : '')?> value="categories[]" />
<?php endif; ?>
</div>
</div>
<?php endwhile; ?>
</div>
Using a HEREDOC:
<div class="boxContentScroll">
<?php
while ($row=mysql_fetch_array($query, MYSQL_NUM)) {
$class = ($row[1]==1) ? 'Yes' : 'No';
$checked = ($class) ? 'checked="checked"' : '';
$data = $row[0];
$admin = (isset($_SESSION['admin']) && $_SESSION['admin']==1) ? 1 : 0;
echo <<< HTML
<div class="boxAddCategory{$class}">
<div class="boxAddCategory1">
{$data}
</div>
HTML;
if ($admin) {
echo <<< HTML
<div class="boxAddCategory2">
<input type="checkbox" value="categories[]" {$checked} />
</div>
HTML;
}
echo <<< HTML
</div>
HTML;
}
?>
</div>
Related
I want to ask about how to change div id in if else condition?
My code
<html>
<div id="div1">
<?php
$page = isset($_GET['page']) ? $_GET['page'] : "";
$page2 = isset($_GET['page2]) ? $_GET['page2] : "";
if ($page == "If1") {
include ".../some.php";
}else if ($page2 == "If2") {
echo '<div id="div2">';
include ".../some2.php";
echo '</div>';
}
?>
</div>
</html>
if im going to page in https://localhost/index.php?page2=If2 i want change <div id="div1> to <div id="div2>
can i get some solution?
sorry for my bad english
Here is one approach for doing that, using the If-else statement before printing the <div ... >
<html>
<?php
$page = isset($_GET['page']) ? $_GET['page'] : "";
$page2 = isset($_GET['page2']) ? $_GET['page2'] : "";
if ($page == "If1") {
echo '<div id="div1">';
}else if ($page2 == "If2") {
echo '<div id="div2">
}
include ".../";
?>
</div>
</html>
Declare variable as html attribute
Declare your variable as a html attribute and assign it via php to your <div>.
<?php
// check if request method is "get"
if ($_SERVER["REQUEST_METHOD"] === "GET") {
if (isset($_GET['page'])) { // if "page"
$divId = 'id="div1"';
} else if (isset($_GET['page2'])) { // if "page2"
$divId = 'id="div2"';
}
}
?>
<html>
<div <?php echo $divId ?>>
<?php include ".../" ?>
</div>
</html>
If you'd like to play around with my code in the browser directly, you can do so here.
Here's the simple answer
<html>
<div id="<?php echo isset($_GET['page2']) && $_GET['page'] == 'IF2' ? 'div2' : 'div1' ?>" >
<!-- rest content -->
</div>
</html>
OR
<html>
<?php $id = isset($_GET['page2']) && $_GET['page'] == 'IF2' ? 'div2' : 'div1' ; ?>
<div id="<?php echo $id; ?>">
<!-- rest content -->
</div>
</html>
Note: You can also use PHP short_open_tag to echo id <?= $id; ?> . If short_open_tag enable in php.ini in server
i need your help in this case; i have module in joomla and want to cutting title with specified a limit from joomla library string.php. i change this code :
<?php if ($params->get('show_title', 1)) : ?>
<h3 itemprop="name">
<?php if ($params->get('link_titles') && $params->get('access-view')) : ?>
<?php echo $this->escape($displayData->title); ?>
<?php else : ?>
<?php echo $this->escape($displayData->title); ?>
<?php endif; ?>
</h3>
to this code :
<?php if ($params->get('show_title', 1)) : ?>
<h3 itemprop="name">
<?php if ($params->get('link_titles') && $params->get('access-view')) : ?>
<a href="<?php echo JRoute::_(ContentHelperRoute::getArticleRoute($displayData->slug, $displayData->catid)); ?>" itemprop="url">
<?php
$limit =100;
if (strlen($this->item->text) > $limit) {
echo (substr($this->item->text, 0, $limit)) . " ... ";
}
else {
echo $this->escape($displayData->title); } ?></a><?php else : ?>
<?php endif; ?>
</h3>
but not work.
thanks for your attention guys.
Joomla has a built-in JHtmlString/truncate method which you can use, I've had good success using it with some of our templates and overrides.
This method would let you simplify your code and you could replace you entire last php block with something like the following
<?php
$limit =100;
echo JHTML::_('string.truncate', ($this->item->text), $limit, false, false);
?>
More about JHtmlString/truncate: https://docs.joomla.org/API16:JHtmlString/truncate
Some example code which might be helpful:
https://gist.github.com/2dpi/a540527a64f9f0093392
https://hotexamples.com/examples/-/JHtmlString/truncateComplex/php-jhtmlstring-truncatecomplex-method-examples.html
Good luck!
I am trying to understand a simple / better way of coding something like this php conditional statement.
<?php if (count($foo_bar) > 1) : ?>
<div class="myDiv1">
Hello!
</div>
<?php endif; ?>
<?php if (count($foo_bar) == 1) : ?>
<div class="myDiv2">
Goodbye!
</div>
<?php endif; ?>
Looking for example, and explanation as to why it may be better. Thanks!
Quite simply in this specific situation you dont need the second if as it can be accomplished with a simple if else
<?php if (count($foo_bar) > 1) : ?>
<div class="myDiv1">
Hello!
</div>
<?php else: ?>
<div class="myDiv2">
Goodbye!
</div>
<?php endif; ?>
<?php
$class = 'myDiv2';
$msg = 'GoodBye!';
if (count($foo_bar) > 1) {
$class = 'myDiv1';
$msg = 'Hello!';
}
?>
<div class="<?php echo $class; ?>">
<?php echo $msg; ?>
</div>
Try using an elseif like below. A bit more compact than the 2 statements.
<?php if (count($foo_bar) == 1) : ?>
<div class="myDiv2">
Goodbye!
</div>
<?php elseif(count($foo_bar) > 1): ?>
<div class="myDiv1">
Hello!
</div>
<?php endif; ?>
First, you should the count function only once.
Second, reduce the duplicated HTML blocks.
<?php
$countFooBar = count($foo_bar);
if ($countFooBar == 1){
$message = 'Goodbye! !';
$cssClass = 'class1';
}elseif( $countFooBar > 1){
$message = 'Hello!'
$cssClass = 'class2';
}
?>
<div class="<?php echo $cssClass ?>">
<?php echo $message; ?>
</div>
This for each / if statement displays changes, and then right below it it displays the changes made.
I am trying to write an if statement that tells it not to show the h2 and the #change_box if there are no changes.
Help would be greatly appreciated.
<h2 class="changes"> Changes: </h2>
<div id="change_box">
<? foreach ($audit['Events'] as $event):?>
<?if ( $event['Type'] != 'Comment'):?>
<span class="field">
<?= $event['Field']?>
</span>:
<?= $event['Value'] ?>
<?=($event['Previous'])?>
<?endif?>
<?endforeach?>
</div>
<?php
if ($changes) { // You'll have to set this variable
//Echo all of your HTML
else {
//Echo the stuff you'd rather show if they didn't change anything
}
?>
To give you an idea of how I'd write your code
<?php
if ($changes) {
echo '<h2 class="changes">Changes:</h2>';
echo '<div id="change_box">';
foreach ($audit['Events'] as $event) {
if ($event['Type'] != 'Comment') {
echo $event['Field'] . </span> . $event['Value'] . $event['Previous'];
}
}
echo "</div>"
}
?>
You could wrap your code with an if like
if(count($audit['Events'])>0)
{
//Your code
}
Wny do you open and close php tags every time? Would be better to make everything in PHP and echo whenever you want to print HTML code.
<?php
echo "<h2 class=\"changes\"> Changes: </h2>";
echo "<div id=\"change_box\">";
foreach ($audit['Events'] as $event) {
if ( $event['Type'] != 'Comment') {
echo "<span class=\"field\">".$event['Field']."</span>";
echo $event['Value'];
echo "(".$event['Previous'] .")";
}
}
echo "</div>";
?>
please make space after each <? and make sure you enabled short tags
<?php if(is_array($audit['Events']) && $audit['Events']):?>
<h2 class="changes"> Changes: </h2>
<div id="change_box">
<?php foreach ($audit['Events'] as $event):?>
<?php if ( $event['Type'] != 'Comment'):?>
<span class="field">
<?php echo $event['Field'];?>
</span>:
<?php echo $event['Value']; ?>
<?php echo $event['Previous'];?>
<?php endif;?>
<?php endforeach;endif;?>
</div>
I've just recently started using PHP 5.4 and have noticed as of 5.3 you can use goto to jump to sections of code which I am using to jump from a loop section. My question is after having read this post... Is GOTO in PHP evil? is this bad practice in this case or is it a viable solution?
<?php
while ($thisResult = mysql_fetch_array($result)) {
if($article && $i > 0) {
goto comments;
}
?>
<h2>
<?=$thisResult['post_title']?>
<span><?=$thisResult['post_modified_gmt']?></span>
</h2>
<p class="content">
<?=nl2br($thisResult['post_content']);?>
</p>
<br />
<?php
comments:
if ($article) {
?>
<p class="comment"><?=$thisResult['comment_content']?>
<?php
}
$i++;
}
?>
This is called spaghetti programming and is a bad practice.
http://en.wikipedia.org/wiki/Spaghetti_code
here is what you can do instead for your code
<?php
while ($thisResult = mysql_fetch_array($result)) {
if($article && $i > 0) {
}
else {
?>
<h2>
<?php $thisResult['post_title']?>
<span><?php $thisResult['post_modified_gmt']?></span>
</h2>
<p class="content">
<?php nl2br($thisResult['post_content']);?>
</p>
<br />
<?php
}
if ($article) {
?>
<p class="comment"><?php $thisResult['comment_content']?>
<?php
}
$i++;
}
?>
A simple else solves it. you can probably find more elegant solutions using switch cases or flags.
The problem is that your code will be hard to edit and add stuff to it.
This is rewrite of the same code without using goto, to show you that you can always make it without it
<?php
while ($thisResult = mysql_fetch_array($result)):
if(!$article || $i <= 0): ?>
<h2>
<?php echo $thisResult['post_title']; ?>
<span><?php echo $thisResult['post_modified_gmt']; ?></span>
</h2>
<p class="content">
<?php echo nl2br($thisResult['post_content']); ?>
</p>
<br />
<?php endif; ?>
<?php if ($article): ?>
<p class="comment"><?php echo $thisResult['comment_content']; ?></p>
<?php endif;
$i++;
endwhile;
I used alternative syntax for control structures, and replaced <?= with <?php echo as it's much more readable to me. Also, other commenters gave you some good suggestions regarding separation of markup and db functions etc, so please give it a thought