Why This Loop Always Produce N+1 Output? - php

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++;
}

Related

How do you print a variable in PHP that's either one element of an array, or the whole variable if it's not an array

Say I have $exampleVariable, which I want to print. $exampleVariable may be an array, in which case I have this set up to get the right array element, which I can then print with print $exampleVariable[$i].
if ($_GET) {
$i = array_search($_GET["exampleQueryString"], $exampleVariable);
} elseif (is_array($exampleVariable)) {
$i = 0;
} else {
$i = "";
}
My problem is that last else, if $exampleVariable is NOT an array, because then I get print $exampleVariable[] which doesn't work. So is there something I can put as $i to print the whole variable?
Alternatively, I considered including the brackets in $i, so I'd have for example $i = [0];, but in that case I don't know how I'd print it. $exampleVariable$i certainly won't work.
I have a good number of variables besides $exampleVariable I'll need to print, all with the same $i or lack thereof, so I'd like to not have to do anything longwinded to set each of them up individually.
This sounds way more complicated than I feel like it should, so hopefully it makes sense!
You can always do a nifty thing that is called type casting. That means, that you can always make a variable an array even if it is not, by prepending its name by (array):
$exampleVariable = (array)$exampleVariable;
So you don't need three if branches at all:
if ($_GET) { 
$i = array_search($_GET["exampleQueryString"], $exampleVariable);
} else {
$i = 0;
$exampleVariable = (array)$exampleVariable;
}
You could apply the (array) cast, which will have no effect if the target is already an array:
$i = array_search($_GET["exampleQueryString"], (array)$exampleVariable);

handle null values to prevent errors while in loop

I am using the following code to return data from a loop and although I am receiving the data it seems there may be null data also which is producing errors.
Here is the code
$extensions = count($cert['tbsCertificate']['extensions']);
for ($j = 0; $j < $extensions; $j++) {
$count = count($cert['tbsCertificate']['extensions'][$j]['extnValue']);
for ($i = 0; $i < $count; $i++) {
if (array_key_exists('dNSName', $cert['tbsCertificate']['extensions'][$j]['extnValue'][$i])) {
$value = $cert['tbsCertificate']['extensions'][$j]['extnValue'][$i]['dNSName'];
$item = $i;
echo 'DNSName',$item,' : ', $value,"\n";
}
}
}
Here is the result of output
Can someone help me update the code to check for null values (i think in the first for loop) and ideally ignore those so the warnings don't appear? I am happy to provide more context if required.
Change your if condition so that it checks if it is set and if it is array first:
if(isset($cert['tbsCertificate']['extensions'][$j]['extnValue'][$i])
&&
is_array($cert['tbsCertificate']['extensions'][$j]['extnValue'][$i])
&&
array_key_exists('dNSName', $cert['tbsCertificate']['extensions'][$j]['extnValue'][$i]))
if it detects in first condition it is not set or is not an array, it will not proceed to array_key_exists function.
The error probably is, because the incoming data has not indexes like 0,1,2,3... - may be it starts from 1.
The easest solution I think is if you replaces FOR structures by FOREACH.

PHP - Exit For Loop After Wrong Answer

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.

lost var in php

I am fairly new to PHP and Yii, and the problem that I am not nor as the question in google, so the only thing I can think of is to ask the question to this list that I have solved many problems.
The issue is as follows: in the code that I attached, I read several records that I keep in array and after the process.
Well, if you look at the debug entries in foreach in he first, all goes well and the variable $items is loaded, but when I get to the second debug $items variable has the correct number of elements, but the elements are empty : count ($items) = 2 but $items[0] and $items[1] are null
$idiomas=CListaMidiomas::model()->findAll();
$items=array();
$nombre=array();
$a=0;
foreach ($idiomas as $idioma){
$nombre[$a]=$idioma->sIdioma;
$items[$a]=TblCategoriastexto::model()->findAll(
array('condition'=>'id='.$data->id.' AND idIdioma='.$idioma->id_idioma));
echo "<br>---AAAAAAAAAAA--".$a."-----------<br>";
CVarDumper::dump($items); //in this moment is correct
if (empty($items[$a]) ||$items[$a]==null ){ // not enter because $items have content
$items[$a]=new TblCategoriastexto();
$items[$a]->idIdioma=$idioma->id_idioma;
}
$a++;
}
echo ">>>>>>>>>>>>>>>".count($items) ; //<<<<<<<<<<present 2
CVarDumper::dump($items); // but in this moment t0 2 are null
for ($a=0;$a<count($items) ;$a++){
echo "<b>".CHtml::encode($nombre[$a]).":</b>";
$out="";
$item=$items[$a];
echo "<br>-----".$a."-----------<br>";
CVarDumper::dump($items[$a]);<<<<<<<<<<<<<<<<<<<<<<<<null
for ($b=1;$b<=20;$b++){
$campo="tc".$b;
$out.=$items[$a]->$campo . ",";<<<<<<<<<<<<<<<<error
}
echo CHtml::encode($out);
echo"<br>";
}
This line: if (empty($items[$a]) ||$items[$a]=null ){ will always assign $items[$a] to null.
To compare values, use the comparison (for equality) operator, == instead of the assignment operator =.
Try changing this line:
if(isset($items[$a]->$campo)) {
$out.=$items[$a]->$campo . ",";
}

Display text once within while loop on the first loop

<?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

Categories