foreach() executing same line again and again - php

I have a sql field wehre values are like
1,2,3,4,5,6
if fetch those values and explode them below
$amenities = 1,2,3,4,5,6
$amenities_check = explode( "," , $amenities );
Then I run a foreach loop
<?php
$i = 1;
foreach($amenities_check as $amenities_conf)
{
if( $amenities_conf != "" && $amenities_conf == 6)
{
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else
{
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}
if ($i++ == 1) break;
}
?>
Now the problem is that this loop is display the same line 6 times and display the correct class of li when it meets the 6 digit in the data if i apply $i++ it only check the first data in the dataset.
Any help that foreach look for the desired values like 1 2 3 and do the function according to it ..
Thanks

Is this what you are looking for?
<?php
foreach($amenities_check as $amenities_conf) {
if ($amenities_conf == 6) {
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else {
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}
}
?>
EDIT:
<?php
foreach($amenities_check as $amenities_conf) {
if ($amenities_conf == 6) {
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
}
?>
<li class="not_amen">Smoking Allowed</li>
or like the guys above said, use in_array().
<?php
if (in_array("6", $amenities_check)) {
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
?>
<li class="not_amen">Smoking Allowed</li>

From the comments, what you actually want to know is if there is a 6 anywhere in the array, so you don't want to be outputting anything at all in the loop. The simplest approach is to use the fairly self-explanatory in_array function; as simple as this:
if( in_array('6', $amenities_conf) )
{
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else
{
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}
Alternatively, break apart your logic from your display by looping through the database result once and preparing structured data based on it. The below is probably over-kill for this example, but shows a general approach:
// While retrieving data from the DB
$amenity_names = array(
1 => 'pets',
// ...
6 => 'smoking'
);
$included_amenities = array();
$amenities_check = explode( "," , $amenities );
foreach ( $amenities_check as $amenity )
{
$name = $amenity_names[$amenity];
$included_amenities[$name] = true;
}
// In the View / template code
if( $included_amenities[['smoking'] )
{
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else
{
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}

Related

Explode and Set if condition php

Array ( [0] => 1 [1] => 2 )
I'm trying to set an if condition based on user permission, the idea is to show menu based on given values, if it is 1, one menu will be displayed and 2 second menu will be displayed, if its both then all values will be displayed. So far for single values i have gotten it right but how to do it for array of values
This is my code
<?php
$userid = $this->phpsession->get("user_id");
$userrole = $this->phpsession->get("user_type");
$query = $this->db->select("role_empid,role_permissions")->from('hw_role')->where('role_empid', $userid)->get()->result();
$data = $query[0]->role_permissions;
if($data == 1){
?>
<li>Add Enquiry</li>
<li>Enquiry List</li>
<?php }else if($data == 2){ ?>
<li>Request For Proposal</li>
<?php } ?>
</ul>
if role_permission contain json object that first convert it into the array like
$data = $query[0]->role_permissions;
$data=json_decode($data);
otherwise direct check the condition for
$data = $query[0]->role_permissions;
if(in_array(1,$data) && in_array(2,$data))
{
}
else if(in_array(1,$data))
{
}
else if(in_array(2,$data))
{
}
If $query[0]->role_permissions is an array that has distinct value, then you can try :
<ul>
<?php for($i = 0; $i<count($data);$i++) {
if($data[$i] == 1){ ?>
<li>Add Enquiry</li>
<li>Enquiry List</li>
<?php }
if($data[$i] == 2){ ?>
<li>Request For Proposal</li>
<?php }} ?>
</ul>
Try This
<?php
if(in_array(1,$data)){
?>
<li>Add Enquiry</li>
<li>Enquiry List</li>
<?php }
if(in_array(2,$data)){
?>
<li>Request For Proposal</li>
<?php } ?>

For loop is making 3600 database requests to load Products. PHP

Problem: One piece (That we can identify currently) is causing a clients product list to call the database over and over again (3600 times) at points when loading a longer list of products.
Code:
<?php foreach ($cats as $cat) :
if (in_array($cat->getId(), [68, 28, 27, 59, 79, 80, 119])) :
$cat_show = Mage::getModel('catalog/category')->load($cat->getId());
$children = $cat_show->getChildrenCategories($cat->getId());
$url1 = $cat_show->getURL();
$showAnyways = in_array(strtolower($cat_show->getName()), ["hats", "juniors", "accessories"]);
if ($cat_show->getShowSidebar() == 1 || $showAnyways) : ?>
<li class="current<?php if ($cat->getId() == $current_cat) { ?> active <?php } ?>">
<?php echo $cat->getName() ?>
<ul>
<?php if ($cat_show->getID() != 68 && $cat_show->getID() != 59) { ?>
<li class="current<?php if ($cat->getId() == $current_cat && $j == 0) {
$j++; ?> active<?php } ?>"><a class="view_all" href="<?php echo $url1 ?>"><?php echo $this->__("View All"); ?></a></li>
<?php } ?>
<?php foreach ($children as $subcat) {
$subcat_show = Mage::getModel('catalog/category')->load($subcat->getId());
if ($subcat_show->getShowSidebar() == 1 || in_array($subcat_show->getID(), [84])) {
$grand_children = Mage::getModel('catalog/category')->getCategories($subcat->getId());
if ($grand_children) {
$cats_displayed = 0;
foreach ($grand_children as $grand_child) {
$grand_child_show = Mage::getModel('catalog/category')->load($grand_child->getId());
if ($grand_child_show->getShowSidebar() == 1) {
$url = Mage::getModel('catalog/category')->load($grand_child_show->getId())->getURL();
?>
<li class="current<?php if ($grand_child->getId() == $current_cat && $j == 0) {
$j++; ?> active<?php } ?>">
<?php echo $grand_child_show->getName() ?>
</li>
<?php $cats_displayed++;
}
}
}
if ($cats_displayed == 0 || !$grand_children) {
$url = Mage::getModel('catalog/category')->load($subcat->getId())->getURL();
?>
<li class="current<?php if ($subcat->getId() == $current_cat && $j == 0) {
$j++; ?> active<?php } ?>">
<?php echo $subcat->getName() ?>
</li>
<?php }
}
} ?>
</ul>
</li>
<?php endif;?>
<?php endif;?>
<?php endforeach; ?>
Can anyone provide me with some pointers on how to make this FAR more efficient and not make so many DB calls.
Should note, I am not an amazing php developer by trade. Main language is python so I am trying to get some advice on the best way to go about fixing this given my less that great knowledge of php itself.
You should never have a database query call inside a for loop. You need to build a query at the start that will get all the data required before the for loop.
Some instant pointers I can see are:
$grand_child_show = Mage::getModel('catalog/category')->load($grand_child->getId());
if ($grand_child_show->getShowSidebar() == 1) {
$url = Mage::getModel('catalog/category')->load($grand_child_show->getId())->getURL();
This is calling the database twice for no reason, you should be able to do this:
$grand_child_show = Mage::getModel('catalog/category')->load($grand_child->getId());
if ($grand_child_show->getShowSidebar() == 1) {
$grand_child_show->getURL();
You should be able to drop all these 'GetModel' functions if at the start of the script you call something like:
$all_grand_children = Mage::getModel('catalog/category')->getAllCategories();
This would return a hash array which you would be able to access relevant items by doing the following inside the for loop:
$grand_children = $all_grand_children[$subcat->getId()];
This would replace
$grand_children = Mage::getModel('catalog/category')->getCategories($subcat->getId());
You should also do a initial call for all of the grand_child and cat_show objects. If you are skilled at SQL you can call just the relevant information by joining the tables in one SQL query.

How to set "class = active" for second tab?

I have some tabs. In that sometimes first tab is "introduction" and sometimes "outline" is first tab. I have set introduction class=active when it comes first. But when outline comes first I am not getting how to set its class as active.
code is like below
<ul class="nav-tabs" role="tablist">
<?php
$tabs = array();
if(!$sessId == "" && !$checkcourse){
$tabs = array("introduction"=>true, "outline"=>true,"announcement"=>false,"discussion"=>false,"review"=>true, "student"=>true, "comment"=>true);
} else if($sessId == "") {
$tabs = array("introduction"=>true, "outline"=>true,"announcement"=>false,"discussion"=>false,"review"=>true, "student"=>false, "comment"=>true);
} else {
$tabs = array("introduction"=>false, "outline"=>true,"announcement"=>true,"discussion"=>true,"review"=>true, "student"=>true, "comment"=>false);
}
?>
<?php if($tabs['introduction']) { ?>
<li class="active">Introduction</li>
<?php } ?>
<?php if($tabs['outline']) { ?>
<li>Outline</li>
<?php } ?>
<?php if($tabs['review']) { ?>
<li>Review</li>
<?php } ?>
<?php if($tabs['student']) { ?>
<li>Student</li>
<?php } ?>
<?php if($tabs['comment']) { ?>
<li>Comment</li>
<?php } ?>
<?php if($tabs['announcement']) { ?>
<li>Announcement</li>
<?php } ?>
<?php if($tabs['discussion']) { ?>
<li>Discussion</li>
<?php } ?>
</ul>
Simple check with ternary operator is:
<?php if($tabs['outline']) {?>
<li <?=$tabs['introduction']? '' : ' class="active"';?>>Outline</li>
<?php } ?>
So you check if $tabs['introduction'] isset then you don't need class="active", else - add this class.
Update:
But as first item of tab can change, I advise to create simple foreach:
$is_first = true;
foreach ($tabs as $tab_name => $value) {
if ($value) {
echo '<li' . ($is_first? ' class="active"' : '') . '>' . $tab_name . '</li>';
$is_first = false; // fix that we have first value here
}
}
Here your main problem is how to link href value and caption.

How to add html inside an if else statement in php?

I have this code where if something then display a link, else display another link. the if and else are php code, and the links are html as you will know, but I was wondering how do you make it so it will not give me any errors, how do I combine php with html?
<?php foreach ($user_socs as $user_soc) {
if ($soca == $user_soc) {
Leave Society;
} else {
Join Society;
}
This might help you. This one is from the basics of PHP:
<?php foreach ($user_socs as $user_soc) {
if ($soca == $user_soc) {
echo "<a href='file.php' class='socbuttons'>Leave Society</a>";
} else {
echo "<a href='anotherfile.php' class='socbuttons'>Join Society</a>";
}
}
?>
Remember PHP should be surrounded by <?php ?>. Simply end the "PHP part" and then start it again when you finished your HTML.
<?php foreach ($user_socs as $user_soc) {
if ($soca == $user_soc) {
?> Leave Society <?
} else {
?> Join Society<?
}
Also, you can write HTML in echo statement, but you should escape some special characters like " to not interfere with the php code itself.
<?php foreach ($user_socs as $user_soc) {
if ($soca == $user_soc) {
echo "Leave Society";
} else {
echo "Join Society";
}
See http://php.net/manual/en/function.echo.php to more information.
Try this
<?php foreach ($user_socs as $user_soc) {
if ($soca == $user_soc) { ?>
Leave Society;
<?php } else { ?>
Join Society;
<?php }
Use alternate syntax:
<?php
$aUserSocs = array( 'link1', 'link2', 'link3' );
$soca = 'link2';
$iCountUserSocs = count( $aUserSocs );
for( $i = 0; $i < $iCountUserSocs; ++$i ):
?>
<?php if( $soca == $aUserSocs[ $i ] ): ?>
Leave Society;
<?php else: ?>
Join Society;
<?php endif; ?>
<?php endfor; ?>

How do I close this php statement correctly?

Im attempting to create a simple list out of some elements I stole from a more complex list of rows etc., I just need list out the values in single row separated by commas.
<?php foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
echo nbf_common::nb_strlen($document_item->product_code);
}
;} ?>
;} ?>
<?php } ?>
The Result I get follows "3 ;} ?> 3 ;} ?> 4 ;} ?> 3 ;} ?> "
Thanks in advance
Micah
try this
<?php
foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
echo nbf_common::nb_strlen($document_item->product_code);
}
}
}
?>
Fore more detail PHP Tags
Change the #9, #10, remove #11 line. What you're doing is printing characters: ;} ?>
and are syntactically wrong. This is proper:
<?php foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
echo nbf_common::nb_strlen($document_item->product_code);
}
} // here
} // here
?>
Also for the "comma separated" part, put required values in a variable and echo it at the end.
Could be like this:
<?php
$string = '';
foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
$string .= nbf_common::nb_strlen($document_item->product_code).',';
}
}
}
echo rtrim($string, ','); // remove the last comma
?>
or use a temp array to glue them at the end:
<?php
$lines = array();
foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
$lines[] = nbf_common::nb_strlen($document_item->product_code);
}
}
}
echo implode(',', $lines); // bind them with comma
?>
I'm not sure why you have all those extra ?>. The pattern is:
<?php
// PHP code goes here
?>
i.e. every <?php has a matching ?>; no more, no less.1
1. Other than the case that #Mihai points out in the comment below...
To understand the php tags you might want to think that you are in an HTML file and you are intrerrupting the HTML flow with
When writing PHP only files (classes, interfaces, traits lists of functions and similar grouping of application code with no templating) it is advisable to open at the very first character in the file and not end it at all.
When writing template files however it is advisable to use php's alternate syntax:
<?php if($x): ?>
<?php elseif($y): ?>
<?php else: ?>
<?php endif; ?>
Instead of the standard:
<?php if($x) { ?>
<?php } else if($y) { ?>
<?php } else { ?>
<?php } ?>

Categories