I am going through a series of values checking if they are the same or different, I want to how many values at the top of the list are the same.
$counter=0;
while ($value<$numberOfValues){
if($valueA == $valueB){
$counter++;
}else{
break;
}
}
echo $counter;
Why does $counter always equals 0 after the break?
Thanks in advance!
Because value and numberOfValues should have a $ in front of them ($value and $numberOfValues), otherwise the while() loop will not run at all and $counter will still be 0.
Related
So I am running into an issue that I figured out how to fix, but I am very curious as to why. So here is a block of code
<?php
function test($attempt=1){
if ($attempt == 5){
echo "Done!";
}else{
echo 'recursion!';
test($attempt++);
}
}
$test = test();
Now this code should run the first time, check, go into the else statement then run test again but this time with $attempt++ until eventually it is == to 5 and then it will echo done and complete. However this does not work and it loops forever. However it can be fixed by assigning the variable to another variable immediately after entering the function like so
<?php
function test($attempt=1){
$nextAttempt = $attempt+1;
if ($attempt == 5){
echo "Done!";
}else{
echo 'recursion!';
test($nextAttempt);
}
}
$test = test();
Any ideas as to why this is?
You want pre-increment instead of post-increment of the variable. This will increment the variable $attempt before passing it as an argument to the function instead of after.
So basically you want test(++$attempt); instead of test($attempt++);.
Sandbox with working example: http://sandbox.onlinephpfunctions.com/code/c50731815588d55bd079e701f1c5dde9e7148696
http://php.net/manual/en/language.operators.increment.php
The operator ++ executes after the evaluation of the sentence, so you are executing the call to the function with the same value ever.
test($attempt++);
is the same than:
test($attempt);
$attempt = $attempt + 1
I'm trying to teach myself PHP. My current exercise combines a form (not included in the code, but it works) that requires the user to enter the name of a city. The loop and the if statement compare the entry with an array of state capitals to return an answer that states whether that city is a state capital or not.
If I leave out the elseif part, the code runs ok, but I have no alternative when the user has entered a city that is not in the array. But with the elseif, the first part of the loop doesn't execute. For example, if I enter "Albany" without the elseif, I get "Albany is the capital of New York." But if I enter it with the elseif statement, it runs the loop until it finds "New York" and it prints "Albany is the capital of New York."
I've googled this, and I've read the books on PHP that I have. And I also know that I'm making a very basic mistake. Any guidance would be greatly appreciated.
for ($i = 0 ; $i < count($stateCapitalNames); $i++)
if ($enteredCity == $stateCapitalNames[$i]) {
print "<p>$enteredCity is the capital of <b>$stateNames[$i]</b>. </p>";
} elseif ($enteredCity != $stateCapitalNames[$i]){
print "<p>$enteredCity is not the capital of a state.</p>";
}
?>
You can use break to leave the for loop.
You should look at array_search to find the index you are looking for. array_search returns false if the capital does not exist.
For instance
$i = array_search($enteredCity, $stateCapitalNames);
if($i !== false)
{
echo "<p>$enteredCity is the capital of <b>",$stateNames[$i],"</b>. </p>";
}
You are missing your brackets in your for loop. I'm surprised the elseif is the culprit and that the code doesn't fail anyways. But here is what I would do, errors aside:
$correct = false;
for ($i = 0 ; $i < count($stateCapitalNames); $i++){
if ($enteredCity == $stateCapitalNames[$i]) {
$correct = true;
$stateNames = $stateNames[$i]; // Updated $stateNames variable
break;
}
}
//You can check $correct here...
if($correct){
print "<p>$enteredCity is the capital of <b>$stateNames[$i]</b>. </p>"; /*Removed [$i] from $stateNames. For some reason, $stateNames[$i] wasn't updating outside the loop, but now it is.
}
This way, no matter what, until the code finds a correct answer, the user is wronge. Once it finds the right answer, it sets it as correct and exits the loop by setting $i to the length of the array.
Let's say I have this inputs :
<input type="hidden" name="block-1" value="001"/>
<input type="hidden" name="block-2" value="012"/>
<input type="hidden" name="block-3" value="002"/>
<input type="hidden" name="block-4" value="005"/>
<input type="hidden" name="block-5" value="008"/>
and I want to process those input using this PHP loop
$i = 1;
do {
$x = 'block-'.$i;
$webBlock = $_POST[$x];
//some codes here
$i++;
}
while (!empty($webBlock));
why I always have 6 outputs? and the last one is blank output. seems that loop always doing n+1. how to make correct loop based on number of inputs given? thanks!
Do you need while?
I'd go with:
$i=0;
foreach($_POST as $name => $value)
{
if( strpos($name , 'block-') !== false ) echo $i . " - " . $name . ": " . $value;
$i++;
}
Believe that should account for items named 'block-n'. The if statement basically says "if block- is anywhere in the name of the field, echo out such and such".
Let me know if you get an error and will amend.
Because you are using a repeat loop, you should use a while loop:
while (!empty($webBlock)){
$x = 'block-'.$i;
$webBlock = $_POST[$x];
//some codes here
$i++;
}
beacause do will get executed at least once what ever may be in while expression .do while is an exit control loop.
Try this:
$i = 0;
do {
$i++;
$x = 'block-'.$i;
$webBlock = $_POST[$x];
//some codes here
}
while (!empty($webBlock));
UPD: The best approach is this:
for ($i = 1; $i <= count($_POST); $i++) {
$webBlock = $_POST['block-'.$i];
//some code here
}
Because You are using Do While loop.I am not sure about your data but i must say that it will execute one more time as you expected.Let us check it by iterating
It will run first time because $webBlock is not empty and same as for 5 times.Now here you want to close the loop but your 5th iteration's condition gets true.Now it will execute once more and show nothing (because there is nothing in $webBlock)and now condition will find that $webBlock is empty.I suggest you to use while loop here.It will solve your issue
I am not a PHP developer so I will just give you general idea about what you are doing.
Actually you are using Do-while loop which is sometimes called Exit Control loop. So, in case of Do-While after executing code your condition will be checked. So, even you didn't get any value in 'webBlock' your code will be executed. So, this is your bug.
Instead of this you can use While loop, Entry control loop. You code is executed if and only if condition is true.
$i = 1;
while (i>0) {
$x = 'block-'.$i;
$webBlock = $_POST[$x];
if(empty($webBlock))
{
break;
}
$i++;
}
<?php
include 'db.php';
$i=0;
$result15=mysql_query("select c.dishes from c");
while($row=mysql_fetch_array($result15))
{
if($row['dishes']!=NULL)
{
$dish[$i]=$row['dishes'];
$i++;
}
}
mysql_close();
$j=0;
while($j<=$i)
{
echo $dish[$j];
$j++;
}
?>
Getting notice: Undefined offset: 2 in F:\xampp\htdocs....on line 18
You mean while($j<$i) there.
Remember, you incremented $i after the last insert. This means that $i will be higher than the maximum key of $dish.
Some thoughts:
Any time you're testing for equality with null, you should consider using is_null (or !is_null). It is more accurate.
This:
$dish[$i]=$row['dishes'];
$i++;
Would be better as:
// obviously instead of $i you would use count($dish) later (or use foreach)
$dish[]=$row['dishes'];
That final while loop would be better as a foreach:
foreach($dish as $val)
{
echo $val;
}
You need to make sure the index exists before echoing it, as so:
while($j<=$i)
{
if (isset($dish[$j])) echo $dish[$j];
$j++;
}
Your second while loop is going to far. You only define dishes up to i-1 and then you loop through it up to and including i. Change it to:
while($j<$i)
<?php
$i = 0;
while(conditionals...) {
if($i == 0)
print "<p>Show this once</p>";
print "<p>display everytime</p>";
$i++;
}
?>
Would this only show "Show this once" the first time and only that time, and show the "display everytime" as long as the while loop goes thru?
Yes, indeed.
You can also combine the if and the increment, so you won't forget to increment:
if (!$i++) echo "Show once.";
Rather than incrementing it every time the loop runs and wasting useless resource, what you can do is, if the value is 0 for the first time, then print the statement and make the value of the variable as non-zero. Just like a flag. Condition, you are not changing the value of the variable in between the loop somewhere. Something like this:
<?php
$i = 0;
while(conditionals...) {
if($i == 0){
print "<p>Show this once</p>";
$i=1;
}
print "<p>display everytime</p>";
}
?>
Yes, as long as nothing in the loop sets $i back to 0
Yes it will, unless the conditions are false from the start or $i was set to 0 inside the loop