how to break children loops only [duplicate] - php

This question already has answers here:
Can you 'exit' a loop in PHP?
(6 answers)
Closed 4 years ago.
I won't break a loop that is in another loop
these are my codes
for ($i = 0; $i < 20; $i++) {
// some codes
for ($i1 = 0; $i1 < 10; $i1++) {
if (a condition)
{
// i want break this loop not parent loop
}
}
// some codes
}
if I use break; parent loop will break too but I won't break only work for child loop
thanks for your answers

break only breaks out of the loop it's called in. If you want to break out of an outer control structure, you can use the optional integer argument to tell break the number of structures it should break out of (e.g., in this case, break 2 would break out of the outer loop).

I used this and its worked
for ($i = 0; $i < 20; $i++) {
// some codes
for ($i1 = 0; $i1 < 10; $i1++) {
if (a condition)
{
$i1=11;
}
}
// some codes
}

Related

Preventing for loop from exceeding condition in PHP [duplicate]

This question already has answers here:
Can you 'exit' a loop in PHP?
(6 answers)
Closed 4 years ago.
How to prevent for loop from exceeding condition?
Loop below returns 25. I want it to return 20.
for ($i = 5; $sum < 23;)
{
echo $sum += $i;
}
This loop is just an example. There will be variables with any value in place of 5 and 23
You have to write your loop differently.
A for loop is designed to run until the conditions evaluates false. In your case, the loop at sum = 20 will still run, becuase sum < 23 evaluates to true. So if you want 20, simply write $sum < 20.
Or if I give it a second thought, you may want to do it like that:
<?PHP
$sum = 0;
for($i = 5; ($sum+$i) < 23;)
{
$sum += $i;
}
echo $sum;
?>

Can I assign same variable for multiple loop

Case 1 loop inside another loop Can I assign both the $i variable for incrementing?
for($i=0; $i < 10; $i++)
{
for($i=0; $i < 5; $i++)
{
echo "You are too cute";
}
}
Case 2 : if it's not inside, Could I declare $i for both?
like this
for($i=0; $i < 10; $i++)
{
}
for($i=0; $i < 5; $i++)
{
}
There are already some answers that are just fine, but here's a slightly different perspective.
It depends on what you mean by "can". You can do this in the sense that it is syntactically correct PHP code.
for($i=0; $i < 10; $i++)
{
for($i=0; $i < 5; $i++)
{
echo "You will never see this text in your browser.";
}
}
But because a loop does not introduce a new variable scope in PHP, it creates an infinite loop.
The outer loop will execute once, then the inner loop will reset $i to 0, increment it to 5, return control to the outer loop, which will execute once, immediately causing the inner loop to start again, resetting $i to 0 and incrementing it to 5, and so on, forever (at least until your script times out). The outer loop can never end because the inner loop affects $i so that it can never satisfy the exit condition of the outer loop.
In other words, just use a different variable for the inner loop. Removing one integer variable is not going to be a noticeable optimization of your code, if that's what you're concerned about.
In the second example, there's no reason not to reuse $i.
Case 1: It will you get a really odd result, check it out here
How to do it properly? Check that out here
for($i=0; $i < 10; $i++){
for($k=0; $k < 5; $k++){
echo "1)".$i." 2)".$k."\n";
}
echo "\n";
}
Case 2: Works fine as stated in above comments and other answer. But, may I also add that in for instance this example.
for($i=0; $i < 10; $i++){
echo $i."\n";
}
echo "\n Outside the loop: ".$i." \n";
for($i=0; $i < 5; $i++){
echo $i."\n";
}
You can acces $i still after the loop has happend. The reason why you can use $i again is because you are declaring it $i =0; again, without interest toward another loop that is currently running (as is happening in case 1).
You can test this example here
Case 1 : No, you cant. you need to create variable individually for each loop.
for($i=0; $i < 10; $i++)
{
for($j=0; $j < 5; $j++)
{
echo "You are too cute";
}
}
Case 2 : Yes you can.
for($i=0; $i < 10; $i++)
{
echo "You are too cute";
}
for($i=0; $i < 5; $i++)
{
echo "You are too cute";
}
Case 1:
Short answer No you can't .
Long Answer .
First you need to understand what actually a variable is and How that Loop actually works .
Each and every variably is actually a reference to memory. In you example you have created a variable named $i and it can't be greater or equal 10 after incrementing value by one.
In the machine level it is translated to an address in the memory. say for example $i points to a random address 0xF25 When ever you loop it and incrementing it, the next address becomes 0xF30.
When ever you write a for loop, compiler automatically assigns a fixed memory address and that address it limited to your variable scope.
What compiler does is, it creates a table for that token($i). In simple form Look below an example
$i(This is the token ) -> 0xF25 (This is the value)
This value is updated when you do $i++
In nested Loop compiler assigns same table(though outer loop cant access inner loop variables). If compiler puts same variable for inner loop, it will be contradictory. Because inner loop may start from memory address 0xE21. In that case when your outer loop increment value by One it will be 0xE22 but as discussed above it needs to be 0xF30 .
That is why compiler does not allow this and we need to use CASE 2 example.

PHP Is it possible to skip two or more iterations?

I am aware we can skip the next iteration with continue in a for loop. Anyway to skip the next x loops (2 or more)?
You actually can't, you can do a dirty trick like
for ($i=0; $i<99; $i++){
if(someCondition) {
$i = $i + N; // This will sum N+1 because of the $i++ in the for iterator (that fire when the new loop starts)
continue;
}
}
If you're iterating with a for loop (as opposed to a foreach loop) you could do something like this:
for ($i=0; $i<$numLoops; $i++) {
if(condition()) {
$i+= $numLoopsToSkip;
continue;
}
}
Take for example, you can define the amount of times you want to loop as you want as $y
<?php
y = 5;
while (true) {
// do something
if (y > 0) {
y--;
continue;
}
// do something else
}
?>
Coming soon in PHP 'X' ;-)
continue += x;

PHP array - start at beginning if over [duplicate]

This question already has answers here:
PHP - Sequence through array and repeat [modulo-operator]
(3 answers)
Closed 9 days ago.
I have an array with 3 entries like that:
0 => "Banana",
1 => "Apple",
2 => "Strawberry"
Now, when using a for-loop like:
for($i = 1; $i < $foo; $i++) {
$myarray[$i] = $fruitarray[$i];
}
And $i gets higher than 2, we run out of this $fruitarray. So what I want to do now is always to start at the beginning of the array when it's over. So that 3 outputs "Banana", 7 "Apple" etc.
What is the best practice to achieve this (especially if $fruitarray contains many entries)?
This is generally accomplished using the modulo operator.
for($i = 1; $i < $foo; $i++) {
$myarray[$i] = $fruitarray[$i % count($fruitarray)];
}
http://php.net/manual/en/language.operators.arithmetic.php
for($i = 1; $i < $foo; $i++) {
$myarray[$i] = $fruitarray[$i%3];
}
Notice the $i%3, this is pronounced "i mod 3" and it means divide i by 3, and return the leftovers. So, 4%3=1, 7%3=1, 11%3=2, etc.
Just make sure $foo is more than 3, and this should wrap around. If $fruitarray is arbitrarily bigger than 3 items, use
$i%count($fruitarray)
One possible solution would be to check for when $i is equal to $foo - 1 and reset it to 1:
for($i = 1; $i < $foo; $i++) {
$myarray[$i] = $fruitarray[$i];
if($i == ($foo - 1))
$i = 1;
}
You should to use the modulus operator (Modulus remainder of $a divided by $b)
for($i = 1; $i < $foo; $i++) {
$j=$i%count($fruitarray);
$myarray[$i] = $fruitarray[$j];
}
http://php.net/manual/en/language.operators.arithmetic.php
Doing this with eager code is essentially intractable, as it would cause an infinite loop:
$i = 0;
$numFruits = count($fruitarray);
while (true) { // infinite loop!
$myarray[$++i] = $fruitarray[$i % $numFruits];
}
But you can come up with working code if, instead of an array, you use a function to fetch the value:
function getFruitAt($index) use ($fruitarray) {
$numFruits = count($fruitarray);
$realIndex = $index % $numFruits;
return $fruitarray[$realIndex];
}
Or, if you want to get fancy, you can use a generator or define your own Iterator type.

Echo out html set number of times - php [duplicate]

This question already has answers here:
make string of N characters
(5 answers)
Closed 2 years ago.
I'm creating quite a complex html <table> layout and at this early stage it quite time consuming for me to copy and paste each <tr> in order to generate dummy content.
My idea was to specify a dummy <tr> as a $var and then output that x number of times using a function as below:
$html = "<tr>//content</tr>";
function dummy_html($html, $times){
$i = 0;
for ($i <= $times) {
echo $html;
$i = $i++;
}
}
echo dummy_html($html, 5);
But this is returning a parse error on the for line any idea why that might be ?
PHP has a function already
echo str_repeat($html,5);
Your for loop is incorrect. It should be something like:
for( $i = 0; $i <= $times; $i++ ) {
echo $html;
}
Update
#Your Common Sense's solution is better: str_repeat (http://php.net/manual/en/function.str-repeat.php)
http://php.net/manual/en/control-structures.for.php
for should use the notation: for (set arguments, conditions, command to run at the end of the loop), therefor should be:
for($i = 0; $i <= $times; $i++)
Also, I would recommend using str_repeat (http://php.net/manual/en/function.str-repeat.php)

Categories