PHP leading zero beginning with 01 not 00 - php

I am using the following PHP in a wordpress theme for comment count...
<?php $i = 0; foreach ($comments as $comment) : ?>
<?php $ii = sprintf("%02d", $i);?>
<?php $i++;echo $ii; echo '. ';?>
(Echo the comment number beginning with 01.)
The problem is that the first comment starts with 00. instead of 01.
Example:
00. John Smith says...
01. Patrick Smith says...
02. Etc..
Does anyone have any suggestions?

You obviously started at 0:
<?php $i = 0; foreach ...
If you wanted it to start at 1, you should code it to do so:
<?php $i = 1; foreach ...
One key to writing good code is understanding exactly what it is you're asking the computer to do.

change your code to have $i start from one.
<?php $i = 1; foreach ($comments as $comment) : ?>
<?php $ii = sprintf("%02d", $i);?>
<?php $i++;echo $ii; echo '. ';?>

Related

php regex matching issue

I have this kind of output:
1342&-4&-6
And it could be more times or less:
1342&-4 (I need to replace it with: 1342,1344)
1340&-1&-3&-5&-7 (I need to replace it with: 1340,1341,1343,1345,1347)
I've tried to use preg_match but with no success,
Can someone help me with that?
Thanks,
<?php
//so if you had sting input of "1342&-4" you would get 2 stings returned "1342" and "1344"?
//1340&-1&-3&-5&-7 --> 1340 and 1341 and 1343 and 1345 and 1347
//$str="1342&-4";
$str="1340&-1&-3&-5&-7";
$x=explode('&-',$str);
//print_r($x);
foreach ($x as $k=> $v){
if($k==0){
//echo raw
echo $v."<br>";
}else{
//remove last number add new last number
echo substr($x[0], 0, -1).$v."<br>";
}
}
output:
13401341134313451347
i used <br> you can use what ever you need or add to a new variable(array)
$array = explode('&-', $string);
$len = count($array);
for($i=1; $i<$len; $i++)
$array[$i] += $array[0] / 10 * 10;
var_dump(implode(' ', $array));

PHP Array Looping & Exploding

I'm not very experienced in using PHP, but I'm having a hard time thinking of a way to do this. I'm reading from a file and exploding on ":" as you can see here.
<?php
$datainfo = file('data.txt');
for($i = 0; $i < count($datainfo); $i++){
$expdata = explode(':', $datainfo[$i]);
}
?>
The issue is that I need to reference specific indexes of the resulted explosion like this.
<p> <?php echo $expdata[1] ?> </p>
I'm getting back an array of the last line inside the data.txt file. I know why It's happening, I just don't know how to get what I want here. (Sorry Very New). Data.txt contain the following.
name:Octopod Juice Stand
balance:20
price:0.5
customers:12
starting:2014-05-26
end: 2014-09-01
juice:15.25
fruit:10
Change your code to
<?php
$datainfo = file('data.txt');
$expdata = array();
for($i = 0; $i < count($datainfo); $i++){
$expdata[] = explode(':', $datainfo[$i]);
}
?>
And then to get the first label.
<p><?php echo $expdata[0][0]; ?></p>
Or the first value
<p><?php echo $expdata[0][1]; ?></p>

PHP Explode function. If function

Could someone help suggest in below php explode function, we are displaying script after 5th listing. How is it possible to display script exactly after 5th listing and 10th listing on a page which has more than 10 listings
We tried using
if ($i == 5 & $i== 10)
but it does not work
Below is original code - which displays script after 5th listing
<?php
$listings = explode("<hr/>", $list);
$numberOfListings = count($listings);
for($i = 0; $i < $numberOfListings; ++$i)
{
if ($i == 5)
{ ?>
<script> </script>
<?php }
echo $listings[$i] . "<hr/>";
}
?>
Edit
How is it like - if have to display a separate script on $i==9, could you advise.
Because $i starts at 0 (0 to 9 is 10, whilst 0 to 10 is 11). Try if ($i == 4 || $i== 9), with an or operator.
Also I would not use the && (the and operator), because it is unlikely $i will ever equal both 4 and 9. I'd suggest you read into Truth Tables (and maybe Propositional Calculus) because from seeing what you had tried originally, it would be helpful to understand how a truth table works.
(source: wlc.edu)
You can use the contine, continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
$arr = range(0,9);
foreach($arr as $number) {
if($number < 5) {
continue;
}
print $number;
}
Ref: http://php.net/manual/en/control-structures.continue.php
Try using modulus operator
$listings = explode("<hr/>", $list);
$numberOfListings = count($listings);
for($i = 1; $i < $numberOfListings; ++$i)
{
if ($i%5 == 0)
{
echo "in";
?>
<script> </script>
<?php
}
echo $listings[$i-1] . "<hr/>";
}
Here we are looping from 1 and there for $i <= $numberOfListings
and while listing we will use $listings[$i-1]
DEMO CODE AT http://codepad.viper-7.com/lrTOgP

Foreach break and continue in PHP

I am facing an problem. I have built a foreach loop in PHP:
<?php $show = false; ?>
<?php foreach ($this->items as $item) : ?>
But I want to echo the first 20 items and continue with the following 16 items.
I have managed to make it to do a break after 20 items but I am not getting the following 16 items ( starting from nr 21 ).
This is what I have so far:
<?php $show = false; ?>
<?php $i = $item->id = 1; ?>
<?php foreach ($this->items as $item) : ?>
<?php if(++$i > 20) break; ?>
If I set $i to '21' it still echos item 1 and so on.
Solution ## Thanks to #dhavald
<?php $show = false; ?>
<?php foreach (array_slice ($this->items, 0, 20) as $item) : ?>
By placing an array_slice in the foreach you can control the items you want show.
So on the next div i want to show item 21 to 36, the only thing i had to change was the 0 and 20 into , 20, 36
To clarify what I am looking for, I have three divs where I want to echo some items onto it. If an user collapse a div on the first there will appear the first 20 items and if a user clicks div2 the next 16 items will appear.
How can I correct this code to make that happen?
As i forgotten to mention, the solutions you bring on helped me really to understand the process but as i used a component generator for Joomla 3.1 there is one row of code that make it a little bit more complex to call the first 20 and second 16 items.
Directly after the foreach loop there is this line of code
if($item->state == 1 || ($item->state == 0 && JFactory::getUser()>authorise('core.edit.own',' com_ncitycatemus.vraagantwoordtoevoegen.'.$item->id))):
$show = true;
How can i manage it than with the loop ? Or do you suggest another way?
Thanks in advance! Really helped me to understand the loop!!
break breaks out of and stops a loop. continue skips the rest of the code in the loop, and jumps to the next iteration.
Using break and continue is in my opinion the wrong approach here. I'd simply use two for loops:
$keys = array_keys($this->items);
$keysLength = count($keys);
echo '<div id="div1">';
for ($i = 0; $i < min($keysLength, 20); $i++) {
echo $this->items[$keys[$i]];
}
echo '</div>';
if ($keysLength >= 20) {
echo '<div id="div2">';
for ($i = 20; $i < min($keysLength, 36); $i++) { //36 being 20 + 16
echo $this->items[$keys[$i]];
}
echo '</div>';
}
Note: This will work with any amount of items in $this->items. If it's under 20, it'll simply skip the next 16, and if it's above 36, it'll simply ignore the rest.
you can use array_slice to get a part of $this->items array and assign it into 3 different variables and loop over them separately.
$itemsDiv1 = array_slice($this->items, 0, 20); // gives first 20 items
$itemsDiv2 = array_slice($this->items, 20, 16); // gives next 16 items
and so on..
Don't use break; use continue;
<?php $i = 0; ?>
<!-- first group -->
<div>
<?php foreach ($this->items as $item) : ?>
<?php
/**
* Check if count divided by 20 has no remainder
*/
if ( (++$i % 20) == 0 ): ?>
</div>
<!-- start new group -->
<div>
<?php endif ?>
<?php endforeach ?>
<!-- end last group -->
</div>
$stockNotNull = StockDetail::where('sku', 10101001)
->where('stock_quantity', '>', 0)->get('stock_id', 'stock_quantity');
$toSell = 14;
// decrements just once for each $stockNotNull
foreach ($stockNotNull as $product) {
if ($toSell < 1) {
return;
}
$product->decrement('stock_quantity');
// $product->stock_quantity--; returns with a null
// dump($product->stock_quantity);
$product->save();
$toSell--;
// dump($toSell);
if($product->stock_quantity === 0) {
continue;
}
}
This is what I got so far, decrementing in the usual manner i.e $variable-- gives me a null value, $product->decrement('stock_quantity') subtracts 1 on each run, even if the stock_quantity field is far greater than the $toSell variable. The logic is there in my head, I'm just having trouble taking the quantity from the current item and moving on to the next only when the stock_quantity is 0.

How Do I Retain Output Indentation?

I have some PHP code like the following (simplified):
<ul>
<?php
for ($Index = 1; $Index <= 10; $Index++)
{
echo("<li>" . $Index . "</li>\n");
}
?>
</ul>
The problem is that for all lines after the first, the output is without indentation. I want to keep my code neat, so I'd like all the <li> elements to be aligned properly.
I tried outputting tabs before each element with \t, but then the first line is indented more than intended. Outputting the tab after the element means the trailing </ul>'s placement will be messed up.
\r does not work at all.
Are there any tricks to keeping output properly formatted, or do I have to live with messy code?
The first line is more indented than you want it to be because of the extra whitespace at the beginning of this line:
<?php
Since that white space is outside the PHP tags, it is output directly. But because it is outside the PHP tags, it is not included in the loop, and will only affect the first line.
You could do this to help avoid it:
<ul>
<?php
for ($Index = 1; $Index <= 10; $Index++) {
echo "\n <li>$Index</li>";
}
?>
</ul>
...and align the <?php ?> tags at the beginning of the lines, or you could do this:
<ul><?php for ($Index = 1; $Index <= 10; $Index++) { ?>
<li><?php echo $Index; ?></li>
<?php } ?></ul>
...but as ridiculous as it seems, this:
<ul><?php for ($Index = 1; $Index <= 10; $Index++) echo "\n <li>$Index</li>"; ?>
</ul>
...is probably the best way to acheive what you are talking about leaving the least room for ambiguity (different PHP versions seem to handle this slightly differently - for instance in PHP 4.3.10 at least, there is an implicit line break after a ?> tag which does not exist in PHP 5 (I think this may have been a bug). That is one of the reasons I don't use mixed HTML and PHP (although I know many people disagree with me on this point) but what I would rather do is this:
<?php
$out = "<ul>\n";
for ($Index = 1; $Index <= 10; $Index++) $out .= " <li>$Index</li>\n";
$out .= "</ul>";
echo $out;
?>
Use spaces. " " * 8, 16, 20, etc...
Or still use \t in your php, then at the very end echo it all out after replacing \t with spaces ,
echo preg_replace('/^\t/', '4_SPACES_HERE', $output_html);

Categories