How would I stop this foreach loop after 3 iterations? [duplicate] - php

This question already has answers here:
Can you 'exit' a loop in PHP?
(6 answers)
Closed 3 years ago.
Here is the loop.
foreach($results->results as $result){
echo '<div id="twitter_status">';
echo '<img src="'.$result->profile_image_url.'" class="twitter_image">';
$text_n = $result->text;
echo "<div id='text_twit'>".$text_n."</div>";
echo '<div id="twitter_small">';
echo "<span id='link_user'".''.$result->from_user.'</span>';
$date = $result->created_at;
$dateFormat = new DateIntervalFormat();
$time = strtotime($result->created_at);
echo "<div class='time'>";
print sprintf('Submitted %s ago', $dateFormat->getInterval($time));
echo '</div>';
echo "</div>";
echo "</div>";

With the break command.
You are missing a bracket though.
$i=0;
foreach($results->results as $result){
//whatever you want to do here
$i++;
if($i==3) break;
}
More info about the break command at: http://php.net/manual/en/control-structures.break.php
Update: As Kyle pointed out, if you want to break the loop it's better to use for rather than foreach. Basically you have more control of the flow and you gain readability. Note that you can only do this if the elements in the array are contiguous and indexable (as Colonel Sponsz pointed out)
The code would be:
for($i=0;$i<3;$i++){
$result = $results->results[i];
//whatever you want to do here
}
It's cleaner, it's more bug-proof (the control variables are all inside the for statement), and just reading it you know how many times it will be executed. break / continue should be avoided if possible.

Declare a variable before the loop, initialize to 0.
Increment variable at the beginning of the body of for-each.
Check variable at the end of the body of for-each.
If it's 3, break.
You have to be careful with this technique because there could be other break/continue in the for-each body, but in your case there isn't, so this would work.

Increment some counter $i at the beggining of the loop and break; when it reaches 3, e.g.:
if ($i++ == 3)
break;

foreach($results->results as $i => $result){
if($i==3) break;
//whatever you want to do here
}

Related

PHP - Use 'file_put_contents' in Loop [duplicate]

This question already has answers here:
How to append data to file using file_put_contents()?
(2 answers)
Closed 2 years ago.
I have a script that moves through a list and if a condition is met, it echoes the line.
Now, rather than echo the line, I'd like for that line to be placed in a txt file.
Here's my code at the moment:
<?php
$list = file('list.txt');
foreach ($list as $x)
{
if (condition1istrue)
{
echo "$x - Condition 1";
}
else if (condition2istrue)
{
echo "$x - Condition 2";
}
else
{
echo "Conditions Not Met";
}
}
?>
Problem: When I use the below code in place of the echo statement, it only adds the last line where the condition is true and deletes all other lines where the conditions were also true.
$file = fopen('office.txt', 'r');
file_put_contents('true.txt', $x);
So build up the file content incrementally in a variable, then write it at the end.
$content = '';
foreach($foo as $bar) $content .= "Another line\r\n";
file_put_contents('file.txt', $content);

How to get last iteration of for loop when limit and increment is dynamic?

I have seen some question related to this one like
How to check for last loop when using for loop in php?
Last iteration of enhanced for loop in java
but I am not getting exact solution because in my case increment and end limit both are dynamic.
Requirement:- I do not want comma after last element printed.
$inc=11;
$end=100;
for($i=1;$i<=$end;$i=$i+$inc){
echo $i==$end?$i:"$i,"; // 1,12,23,34,45,56,67,78,89,100
}
In above code I know that last element($i) will be 100($end).
So I can write condition as $i==$end but in below case it won't work.
$inc=12; // Now $inc is 12
$end=100;
for($i=1;$i<=$end;$i=$i+$inc){
echo $i==$end?$i:"$i,"; // 1,13,25,37,49,61,73,85,97,
}
Now last element 97 has comma which I need to remove.
Thanks in advance.
Keep it simple:
$numbers = range(0, $end, $inc);
$string = implode(",", $numbers);
echo $string;
You can see it here: https://3v4l.org/BRpnH
;)
You can just use,
echo $i+$inc>$end?$i:"$i,";
It checks whether this is the last possible iteration instead.
Use rtrim to remove the last comma
$inc = 12; // Now $inc is 12
$end = 100;
$print = '';
for($i=1;$i<=$end;$i=$i+$inc){
$print .= ($i==$end)? $i : "$i,"; // 1,13,25,37,49,61,73,85,97,
}
$print = rtrim($print, ',');
echo $print;
You can do it in this way :
<?php
$inc=4;
$end=10;
for($i=1;$i<=$end;$i=$i+$inc){
echo ($i+$inc-1)>=$end?$i:"$i,"; // 1,5,9
}
?>
This code is working on prime number case also not given you result like // 1,13,25,37,49,61,73,85,97, always gives you result like // 1,13,25,37,49,61,73,85,97 no comma added after any prime number.

PHP: Echo something for each 2 results

I have a simple foreach loop that outputs the information I want.
However, I want to wrap it with a div for every two results.
I tried the modulus operator with no success (the result applied for every result).
So, my code:
foreach ($result->data as $info) {
// A open div to wrap two results
echo 'something';
// An closing div to wrap the previous two results
}
This will do it!
foreach ($result->data as $i=>$info) {
if ($i % 2 == 0) echo '<div>';
echo $info;
if ($i % 2 == 1) echo '</div>';
}
if (count($result->data) % 2 == 1) echo '</div>';
exactly what you asked ;)
Most simple way: Iterate in steps of 2.
for ($cc = 0; $cc<count($result->data); $cc += 2) {
// here >> start div container for both
echo $result->data[$cc];
if (defined($result->data[$cc+1]))
echo $result->data[$cc+1];
// here >> end div container for both
}
HTML omitted for clearness.
You can also add an else branch to output a placeholder if the result contains an odd number of items.
add an index count then check that its divisible by two in the code.
IN THIS CASE the if block needs to be at the top of the foreach loop, since I started $i at 0. Please stop editing that portion :)
$i = 0;
// Create first new div before loop, here.
echo '<div>'; //first div
foreach ($result->data as $info) {
// An closing div to wrap the previous two results
if ($i % 2){
// Code here would occur after each two iterations
// IE: close div then open new one. something like this
echo '</div><div>';
}
// A open div to wrap two results
echo 'something';
$i++;
}
// close final div after loop, here.
echo '</div>';
For outputting every two results from array you can also use
<?php
$array = range( 1, 20 );
foreach( array_chunk( $array, 2 ) as $pair ) {
echo '<div>' , implode( ' ', $pair ) , '</div>';
}
// <div>1 2</div>
// <div>3 4</div>
// etc
?>
set 2 variables, string and int
save the value in string variable if the value of the int variable is not even
when the second variable is an even number
wrap in div
//just simply
<?php
foreach($result->data as $i=>$info){
if($i<5){
echo $info
}
}
?>

php : iterate through foreach n-1 times where n value is unknown [duplicate]

This question already has answers here:
Can you 'exit' a loop in PHP?
(6 answers)
Closed 3 years ago.
Here is the loop.
foreach($results->results as $result){
echo '<div id="twitter_status">';
echo '<img src="'.$result->profile_image_url.'" class="twitter_image">';
$text_n = $result->text;
echo "<div id='text_twit'>".$text_n."</div>";
echo '<div id="twitter_small">';
echo "<span id='link_user'".''.$result->from_user.'</span>';
$date = $result->created_at;
$dateFormat = new DateIntervalFormat();
$time = strtotime($result->created_at);
echo "<div class='time'>";
print sprintf('Submitted %s ago', $dateFormat->getInterval($time));
echo '</div>';
echo "</div>";
echo "</div>";
With the break command.
You are missing a bracket though.
$i=0;
foreach($results->results as $result){
//whatever you want to do here
$i++;
if($i==3) break;
}
More info about the break command at: http://php.net/manual/en/control-structures.break.php
Update: As Kyle pointed out, if you want to break the loop it's better to use for rather than foreach. Basically you have more control of the flow and you gain readability. Note that you can only do this if the elements in the array are contiguous and indexable (as Colonel Sponsz pointed out)
The code would be:
for($i=0;$i<3;$i++){
$result = $results->results[i];
//whatever you want to do here
}
It's cleaner, it's more bug-proof (the control variables are all inside the for statement), and just reading it you know how many times it will be executed. break / continue should be avoided if possible.
Declare a variable before the loop, initialize to 0.
Increment variable at the beginning of the body of for-each.
Check variable at the end of the body of for-each.
If it's 3, break.
You have to be careful with this technique because there could be other break/continue in the for-each body, but in your case there isn't, so this would work.
Increment some counter $i at the beggining of the loop and break; when it reaches 3, e.g.:
if ($i++ == 3)
break;
foreach($results->results as $i => $result){
if($i==3) break;
//whatever you want to do here
}

for() loop fails to stop looping ?

I'm trying to print an array until it's empty.
Here is my code:
for ($i=0; $array[0][$i]!=NULL; ++$i){
echo $array[0][$i];
}
However it looks like it performs the echo one extra time, I don't know why ?
Here's my output for an array that contains data up to array[0][2].
I am sure that array[0][3] is empty, I tried it with if(array[0][3]==NULL)
Test 0
Test 1
Test 2
( ! ) Notice: Undefined offset: 3 in C:\... on line 9
Any idea ?
You should use the arrays length when you loop... Or try this instead:
foreach($array[0] as $val) {
echo $val;
}
It makes perfect sense, really. PHP can not magically know that the next id (in your example, index number '3') is not set, it has to access the variable to determine that. That's also why you get the notice.
In short, it does not execute the body of the for loop, but it has to execute the test to determine whether or not to continue.
Anyway, use a foreach loop, or calculate the number of items in the array first and increment $i till they match.
Possible alternatives to you code that should actually work.
foreach($array[0] as $val)
if($val===null)
break;
else
echo $val;
or
$arrlen=count($array[0]);
for($i=0;$i<$arrlen;$i++)
if($array[0][$i]===null)
break;
else
echo $array[0][$i];
or even
$i=0;
while($array[0][$i]!==null) { //not recommended, can cause infinite loop
echo $array[0][$i];
$i++;
}
The reason why it's throwing an error is because an array index that does not exist is not equal to NULL. You can modify your code to this:
for ($i=0; isset($array[0][$i]); ++$i){
echo $array[0][$i];
}
Or try this instead:
$ctr = count($array[0]);
for ($i = 0; $i < $ctr; $i++) {
echo $array[0][$i];
}
The loop should finish after reaching the end of the array.

Categories