For loop is not working properly-its skipping sometimes - php

I have a product called customized gift box with different sizes like 5,9,12 etc.
When the users select items to the gift box and add to cart, I am fetching those chocolate names too with the Quantity of the chocolate.
In the code below, I have written if the product name includes customized then fetch the related chocolate using session in a for loop.
And the For loop is working properly but, sometimes it doesn't.
How can this be resolved?
<?php
if(stristr($this->getProductUrl(),"customized")){
?>
<div>
<?php
echo "<br/>";
$itid = $_item->getId();
echo $itid;
$strrep = str_replace(' ','_',$this->htmlEscape($this->getProductName()));
for($k=1;$k<=sizeof($_SESSION[$strrep."item".$itid]);$k++){
if($_SESSION[$strrep."item".$itid][$k]!=""){
echo " <font size='1px'>".$_SESSION[$strrep."qty".$itid][$k]." x ".$_SESSION[$strrep."item".$itid][$k]."</font><br/>";
}
}
?>
</div>

Your for loop starts with 1 and finishes with the sizeof's element. Array indices are zero based in PHP so you should do
for ($k=0;$k<count($_SESSION[$strrep."item".$itid]);$k++){
...
}
instead. I also replaced sizeof() by count() but that is a matter of preference ...

Related

How to get a foreach statement output in an array with if statement to implode with commas in Wordpress + ACF?

I am making a artist portfolio site in wordpress. I am working on a single page for a custom post type Artwork, which contains numerous metadata fields created using ACF. I have run into trouble displaying the contents of an ACF repeater field with the names of collaborators, if there are any, who contributed to the artwork linked to their personal sites if they have one. This repeater is cloned as one element into the Artwork Field group.
I have been able to display the collaborators' names with and without links using the code below. So it will display "Co-creators: Name1 (with href)Name2 (no href)". But the commas don't show up between the collaborators. I think it is because I am not creating the arrays properly.
Any help would be greatly appreciated.
<?php
while (have_posts()) : the_post();
// lots more code here
$artwork_collaborators = get_field('artwork_collaborators'); // get the value of the acf clone field
if ($artwork_collaborators) : // check if has data ?>
<dd id="single-artwork-collaborators"><?php
_e('Co-creators: ', 'aopa'); // multilanguage label for translation
foreach ($artwork_collaborators as $artwork_collaborator) : // foreach loop to get all collaborators
if ($artwork_collaborator['artwork_collaborator_url']) : // check if there is a url for the collaborator
$array_collaborators = array('' . $artwork_collaborator['artwork_collaborator_name'] . ''); // create array with URL
else :
$array_collaborators = array($artwork_collaborator['artwork_collaborator_name']); // create array without url
endif;
$collaborator_string = implode(", ", $array_collaborators); // implode the array and add commas
echo $collaborator_string; // echo the collaborators with link or no link separated by commas if there is more than one
endforeach; ?>
</dd>
<?php endif;
// lots more code here
endwhile?>
I ended up getting some help on this problem from a programmer friend. Now the output is "Co-creators: Name1 (with href), Name2 (no href)" with the commas in the right place and the link in place when needed and not there when not.
One of the main problems was that the implode and the echo were inside the loop. This was causing them to repeat too many times.
We also created an empty array off the top, then added all the strings into that. See the comments in the code below:
<dd id="single-artwork-collaborators"><?php
_e('Co-creators: ', 'aopa'); // multilanguage label for translation
$collaborators_all = []; // Create an empty Array
foreach ($artwork_collaborators as $artwork_collaborator) : // foreach loop to get all collaborators
if ($artwork_collaborator['artwork_collaborator_url']) : // check if there is a url for any of the collaborators
$collaborator = '' . $artwork_collaborator['artwork_collaborator_name'] . ''; // add rows in loop to the variable
else : // check if there are any collaborators without URLS
$collaborator = $artwork_collaborator['artwork_collaborator_name']; // add these rows in loop to the variable
endif;
$collaborators_all[] = $collaborator; // combine in the array created above all the rows of collaborator names, with and without and links, if there are any of each
endforeach;
$collaborator_string = implode(", ", $collaborators_all); // implode the array and add commas
echo $collaborator_string; // echo the collaborators separated by commas if there is more than one ?>
</dd><?php
endif; ?>

removing line breaks in php

As the title reads I am using the echo function to create an h3 string which will insert a php value $lowprice and $highprice. The goal is to have the text read
Here are all the houses whos prices are between $lowprice and $highprice. The code breaks into individual lines like this
Here are all the houses whose prices are between $
100000
and $
500000
:
This is the code I have written, how do I get it all onto one line.
<?php
echo '<caption>';
echo '<h3> Here are all the houses whose prices are between $ </h3>'.$lowprice.'<h3> and $</h3>'.$highprice.'<h3> : </h3>';
echo '</caption>';
?>
<h3> is a block element, meaning it will take up a whole line. I think you want to replace your inner <h3>'s with <span> tags which are inline elements:
Like this:
<?php
echo '<caption>';
echo '<h3> Here are all the houses whose prices are between $ <span>'.$lowprice.'</span>
and $<span>'.$highprice.'</span></h3>';
echo '</caption>';
?>
Or you can simply remove all the inner tags all together, like this:
<?php
echo '<caption>';
echo '<h3> Here are all the houses whose prices are between $'.$lowprice.' and $'.$highprice.'</h3>';
echo '</caption>';
?>
The line breaks appear because you've made several h3 elements. You're closing and reopening h3 tags at every insertion, which is not necessary. The html output of your code is the following:
<h3>Here are all the houses whose prices are between $</h3>
<h3>100000 and $</h3>
<h3>500000 : </h3>
Which automatically adds breaks, since that is the behaviour of h3 elements.
What you need is this:
echo '<h3> Here are all the houses whose prices are between $'.$lowprice.' and $'.$highprice.':</h3>';
Better yet, don't use echo to define your html; html and php are interchangeable within the same file. A cleaner, more readable and more easily maintainable solution would be to form your script like this:
<caption>
<h3>Here are all the houses whose prices are between $<?= $lowprice ?> and $<?= $highprice ?>:</h3>
</caption>
Generally, you switch between php and html like this:
<?php
...do some php
?>
<somehtml></somehtml>
<?php do some more php ?>
<morehtml>...
Note that <?= is a shorthand for <?php echo.

How to display a list of check box items one per line

I have a list of items that a user can select from when listing their house. I then display these on the frontend using the following:
<? if($group[property_amenities] != "") { ?>
<hr>
<h2 class="vmargin">Amenities</h2>
<?php echo $group[property_amenities]; ?>
<? } ?>
The issues is that I believe I don't have access to change the HTML and the items are listed as follows:
Amenities
Open Plan,Carpeted Floors,
How can I modify the above code to display the items in separate rows, as well as remove the "," or replace the "," with something like " - "
Use str_replace to replace all the commas with break tags, or dashes, or whatever you want.
<?php echo str_replace(',', '<br>', $group[property_amenities];) ?>

SUM and average weight PHP

I'm working on something that calculates me total weight of my class and average weight of my class. In $T I entered weight of girls in class, in
Echo "SUM OF WHOLE CLASS IS : $s";
must be SUM of weight of whole class and
echo "<br/>AVERAGE WEIGHT IS $p";
is average weight of class.. I dont see where the problem is, it just says that is on line number 4..
<body>
<?PHP
$T=array (47,47,62,60,71,55,50,52,62,80,65);
$s=0; $BUB=0;
for ($BUB=0;$BUB<=11;$BUB++)
{
$s=$s+$T[$BUB];
$BUB++;
}
$p=$s/11;
echo "SUM OF WHOLE CLASS IS : $s";
echo "<br/>AVERAGE WEIGHT IS $p";
?>
</body>
Make it simple using the array functions of PHP !
<?php
$T=array (47,47,62,60,71,55,50,52,62,80,65);
echo "SUM OF WHOLE CLASS IS : ".array_sum($T); //"prints the sum
echo "<br/>AVERAGE WEIGHT IS ".array_sum($T)/count($T); //"prints" the average
Demo
Try replacing that: $BUB<=11 with $BUB<11.
Notice that $BUB start with the value 0. as well as the array. so $T[11] isn't exists.

Show available stock quantity on product page

Firstly I would like to apologise if this question has been answered somewhere else but I am unable to find what I am looking for as I am new to PHP and assume I need this to solve my problem.
I have built a website and am using Mals-e shopping cart. I have everything up and running but I would like to show how many products are still in stock under the product description and if there are no items in stock. For example:
Available stock: 2
or
Sold Out
I have read that I need a text file with product name, price and quantity, a PHP file to read and rewrite the quantity available and out put the results on the product page and a mypage.php page but I really don't know where to start. I've spent days trying to sort this out.
I have Mysql database with some items in table called (items) with available quantity but don't know how to go about sorting it out. Any help would be most appreciated.
Thank you.
Without seeing the actual code you're using to display the product, it's hard to say buy all you should need is something like:
<?php
// get the product and stock level
if($product->numberInStock > 0) {
echo 'Available: ' . $product->numberInStock;
} else {
echo 'Out of stock';
}
If you're editing a phtml type template (HTML with embedded PHP), you might display it like:
<? if($product->numberInStock > 0): ?>
<p>Available: <?= $product->numberInStock; ?></p>
<? else ?>
<p>Out of stock</p>
<? endif; ?>
Had same issue, found out following.
Inside your catalog/product type template you can use this:
<?php
$_product = $this->getProduct();
$_qty = $_product->getStockItem()->getQty();
?>
<p>
<?php if($_qty > 0): ?>
Available: <?php echo $_qty; ?>
<?php else: ?>
Out of stock
<?php endif; ?>
</p>
session_start($_POST['quantity']);
if(isset($_POST['quantity']))
{
$postedquantity=$_POST['quantity'];
$productQuantity="20";
if($postedquantity<$productQuantity){
echo "In stock";
echo "<br/>";
}
$productQuantity=$productQuantity-$postedquantity;
echo $productQuantity."Remaining";
}
You can even do like this,storing quantity value in session and everytime it's posted it will check whether it is in stock or not and it will show how much quantity is remaining.

Categories