How can I make a PHP counter? - php

I know I have done this in Javascript once, but how can I make it in PHP?
Basically I want to do this:
if (empty($counter)){
$counter = 1;
}else{
"plus one to $counter" ($counter++?)
}
But it didn't work when I tried. How would I go about doing this?
Thank you :)
EDIT: This is so I can do:
if ($counter == 10){
echo("Counter is 10!");
}
EDIT:
This is all in a "while()" so that I can count how many times it goes on, because LIMIT will not work for the query I'm currently doing.

why the extra if into the while?
i would do this:
$counter = 0;
while(...)
{
(...)
$counter++;
}
echo $counter;

To increment a given value, attach the increment operator ++ to your integer variable and place it within your while loop directly, without using a conditional expression to check if the variable is set or not.
$counter = 1;
while(...){
echo "plus one to $counter";
$counter++;
}
If your counter is used to determine how many times your code is to be executed then you can place the condtion within your while() expression:
while($counter < 10){
echo "plus one to $counter";
$counter++;
}
echo("Counter is $counter!"); // Outputs: Counter is 10!

You're going to have to learn the basics of how PHP outputs to the screen and the other controls along with it.
if (empty($counter)){
$counter = 1;
}else{
echo 'plus one to $counter';
$counter++;
}
Something along those lines will work for you.
PHP is pretty flexible with what you throw at it. Just remember, statements need a semicolon at the end, and if you want to output to the screen, (in the beginning) you'll be relying on echo statements.
Also, when dealing with echo statements, notice the difference between single quotes and double quotes. Double quotes will process any contained variables:
$counter = 3;
echo "plus one to $counter"; // output: plus one to 3
echo 'plus one to $counter'; // output: plus one to $counter

Related

PHP nesting for loop inside for loop

Been trying to figure this one out for the last 3 hours and so hard to find any search results for "nesting for loop inside for loop", so I must ask this question and somebody can help clarify, as much of an amateur question this is, will much appreciate any and all help.
So I have this block of code underneath, for a beginners looping exercise I found at http://www.w3resource.com/php-exercises/php-for-loop-exercises.php
on question 3 of that page. The end result should be on that page as well.
<?php
for($a = 1; $a <= 5; $a++) {
for($b = 1; $b <= $a; $b++) {
echo "*";
if($b < $a) {
echo " ";
}
}
echo "<br />";
}
?>
It turns out like a triangle shape made up of 15 little *
I am trying to figure out exactly how this works, as even though the site has an answer, I want to understand so I can write things myself instead of copy pasting.
Below is what I have been able to make out after reading php.net and also trying to look for a solution on Google.
So, the $a for loop starts off as true so loop continues onto the $b FOR loop, it is true so it will echo *, At this point $b is not < $a as loop is not yet over so the ++ have not been added yet and if statement is false, so we <br /> and re-run loop.
Second time around. Now $a=2 and for loop is still true so it will go on to $b for loop and echo *. This is where I get confused. The $b has ++ at the end of its statement, so doesn't it mean that after loop 1 $b = 2 and if is still false ?
In my head I keep thinking it should print out like:
<br />* <br /> * <br />
instead of this:
<br />* <br /> * * <br />
My conclusion.
The $b value will reset back to 1 after each loop and repeats itself until if statement is false.
OR
The * that get printed are stored and will be the automatic starting point at the beginning of each loop. I understand that if doing a simple print for a for($i=0;$i<11;$i++) loop will carry the value over, however in my situation, a printed * is not a value, so it shouldn't be carried over to a new loop.
OR
I am just completely off with both my conclusions.
Either way, its been confusing me so badly.
Sorry for long explanation.
Thanks.
Let's take things one step at a time
Outer Loop
for($a = 0; $a <= 5; $a++) {
//inner loop here
echo "<br>"; //after the inner loop has executed, start a new line
}
Start at 0, go up to 5 and do whatever is written inside. Now that means two things will happen for each iteration
1) Inner loop will be executed for every iteration of the outer loop
2) An HTML row break will be printed for every iteration of the outer loop
Now what does the Inner Loop do?
for($b = 1; $b <= $a; $b++) {
echo "*";
if($b < $a) {
echo " "; // $b<$a means we still have more stars to print on this line
}
}
Start at 1, go up to the value of $a, this $a will come from the outer loop and will be 1 for the first run, 2 for second up to 5. And while doing this, print a *; that means for the first time 1 star will be printed because loop will start at 1 and end at 1. For the second time 2 stars, 3rd time three stars and so on.
Now after printing the star, see if this is the last star that this iteration had to print, if it is not that then print a space so that the next time a star is printed there is a space in between.
That's about it :) Note that your outer loop starts at 1, it should start at 0 to form the required shape correctly.
Now if you are still confused about the $b<$a thing, just get rid of it and run your code again and you will notice nothing much has changed except that there are no spaces between the stars and it will be a little easier to understand
for($b = 1; $b <= $a; $b++) {
echo "*";
}
And oh, ++ after a variable means increment its value by 1. In a for loop that means on the next run add 1 to the value of the counter. You can also write it as
for($a=0; $a<=5; $a=$a+1) // thats the same as $a++;
If you wanted the value to increment by more than 1 you could say
for($a=0; $a<=5; $a=$a+2) // a will be 0 , 2, 4
Fiddle

How to print php info inside <a> tags, etc?

Is there a way to print php variables inside a HTML tag?
Like this:
<?php
for ($e = 1; $e <= 30; $e++) {
for ($i = 1; $i <= 40; $i++) {
print ('<div id="map"><a>$i</a></div>'); // <----I'm adding the divs here, but I want to add a text inside each of them
}
}
?>
Your call:
echo ''.$title.'';
or
echo "<a href='$href'>$title</a>";
or
<?= $title ?>
I prefer the first one, because I think it is the most readable. But it is up to you.
Using your example:
print ('<div id="map"><a>'.$i.'</a></div>');
or
print ("<div id=\"map\"><a>$i</a></div>"); // note the double quotes to allow PHP to parse the string
or
<div id="map"><a><?= $i ?></a></div> // but you really should do this!
To better clarify you SHOULD NEVER rely on short tags (the last option). Every time you do that god will kill a kitten and abuse a unicorn.
In this case take the variable out of the string and concatenate it inside.
print ('<div id="map"><a>'.$i.'</a></div>');
This is pretty basic stuff so I suggest you go through some tutorials or read the manual again.
I'm not sure what text you want to add there, you can have any other variables in there, same how you're printing the $i .. except that single quotes do not evaluate variables inside the string, only double quotes do ..
so:
$foo = "bar";
print "$foo" => "bar"
print '$foo' => "$foo"
You're using single quotes to output your variable. using double quotes may work instead, but I prefer using string concatenation(. operator)
print ("<div id=\"map\"><a>$i</a></div>");
Or
print ('<div id="map"><a>' . $i . '</a></div>');
Use " instead of ' when you want to use variables in a string.
<a href='<?php echo "http://www.stackoverflow.com"; ?>' target='_blank'>test</a> (Syntax maybe off)
EDIT
<?php
for ($e = 1; $e <= 30; $e++) {
for ($i = 1; $i <= 40; $i++) {
print ('<div id="map"><a>'. $i .'</a></div>');
}
}
?>
Note the '. $i .' part.

How do you remember the order of the expressions in a for loop?

It's a pretty simple question, I always have to go check here and then I hit my head and say it's so obvious. But really after a week of not using it I usually end up writing
for ($i = 1; $i++; $i <= 10;) {
echo $i;
}
some Mnemonic might help
ICE:
Initialisation
Check
Execute
Think logical! The order is the same as the expressions are evaluated.
for ($i = 0; $i < 10; ++$i) {
echo $i;
}
// is same as
$i = 0; // 1.
while ($i < 10) { //2.
echo $i;
++$i; // 3.
}
They go in order.
for (expr1; expr2; expr3)
expr1: Evaluated once at the beginning of the loop
expr2: Evaluated at the beginning of each iteration of the loop
expr3: Evaluated at the end of each iteration of the loop
You want to initialize first, check the condition second, and increment (or decrement) your counter last.
START -> CHECK FOR DANGER -> MOVE AHEAD
for( $i = 0 ; $i < 100 ; $i++ )
Hope it helps :-)
Best of luck!
F
irst (initialisation)
O
Only while (condition)
R
Rolling on (incrementing or decrementing)
I may be daft but don't you want this structure:
for ( $i = 1; $i <= 10; $i++ )
{
echo $i;
}
I don't know of a Mnemonic to remember this structure I've always just seen it as:
STARTING OFF; DO WHILE THIS; PERFORM AFTER EACH ROTATION
Rather:
DEFINE PRIOR TO EXECUTION; DEFINE EXECUTION LIMITS; DEFINE OPERATION FOR EACH ROTATION
Just remember that the guard is always checked before the increment, so you write it before.
If you don't remember the guard is checked before the increment, you're in bigger trouble, because you don't know what the loop will do :p
SAM
Start your engine
Are we there yet?
Move

change a variable based on even/odd status of another variable?

for($i=0;$i<$num;$i++) {
if($i==even) $hilite="hilite";
dothing($i,$hilite);
}
This is basically what I want to accomplish.
What is the most efficient way to determine if $i is even?
I know I could check if half == mod 2 ... but that seems a little excessive on the calculations? Is there a simpler way?
if ($i % 2 == 0)
The already mentioned % 2 syntax is most used, and most readable for other programmers. If you really want to avoid an 'overhead' of calculations:
for($i = 0, $even = true; $i < $num; $i++, $even =! $even) {
if($even) $hilite = "hilite";
dothing($i,$hilite);
}
Although the assignment itself is probably more work then the '%2' (which is inherently just a bit-shift).
It doesn't get any simpler than $i % 2 == 0. Period.
Change the i++ in the loop statement to i+=2, so that you only examine even values of i?
Typically, a number is odd if it's LSB (Least Significant Bit) is set. You can check the state of this bit by using the bitwise AND operator:
if($testvar & 1){
// $testvar is odd
}else{
// $testvar is even
}
In your code above, a more efficient way would be to have $i increment by 2 in every loop (assuming you can ignore odd-values):
for($i=0;$i<$num;$i+=2){
// $i will always be even!
}

How to increase number of iterations from within the loop in php?

I'm working on custom pagination system and encountered following problem. When one of the elements is filtered out of the set, the size of the final array is smaller than needed. Therefore I'm looking for a solution to increase the number of iterations from within the loop to always get array consisting of 50 elements.
$limit = 50; //Number of elements I want to fetch
for($x=0; $x<$limit; $x++){
if ($elementIsNotFiltered) {
//add element to $someArray;
}
else {
//increase the number of iterations, so even if some elements are filtered out,
//the size of $someArray will always be 50
}
}
Thanks for any help.
Do it in a while() loop instead, and break when you finally hit your $limit
Use a while loop.
while(count($somearray) < 50 && /*elements remain*/) ...
else {
++$limit;
}
Tried that?
You may also do the same thing the other way round:
else {
--$x;
}
Or be a little bit more effective:
$x = 0;
while ($x != 50) {
if ($notFiltered) {
++$x;
}
}
If you want to save the counter variable, too, you may use:
while (!isset($array[49])) {
}
The !isset($array[49]) here is only a synonym of count($array) < 50.
It sounds to me like you're looking for a while loop - not a for loop:
while ($items < 50 && [more items to filter]) {
if ([add to array]) {
$items++;
}
}
If you really want to do it in your for loop you can always modify $x but this makes your code unreadable and hard to maintain - I would recommend not doing this...

Categories