I have programmed a script with the goto command but on the server where I want to execute the script there is a previous PHP version (<5.3), so I have to change the code. The structure of the code goes like that:
for($i = 0; $i < 30; $i++) // print 30 articles
{
$x = 0;
// choose a a feed from the db
// parse it
a:
foreach($feed->get_items($x, 1) as $item)
{
// create a unique id for the article of the feed
if($id == $dbid)
{
// if this id exists in the db, take the next article of the same feed which is not in the db
$x++;
goto a;
}
else
{
// print the original article you grabbed
}
} // end of foreach
} // end of for
I have tested everything. Do you have any ideas how can I retransform this code without goto in order to be executed properly???
This questions demonstrates why goto should be avoided. It lets you get away without thinking about the algorithm enough.
The standard way to do this is with a flag. I hope you were not expecting a "herezthecode kthxbai" sort of an answer, but in this case the best way to explain it would be to write the code -
for($i=0;$i<30;$++){
$x=0;
do {
$found = false;
foreach($feed->get_items($x,1) as $item){
// get $id
if($id==$dbid){
$found = true;
break;
}else{
// other things
}
}
$x++;
} while($found);
}
Without knowing how the ->get_items() call behaves you could use this brute-force method in lieu of the goto-switch:
for($i = 0; $i < 30; $i++)
{
$x = 0;
$a = 1;
while ($a--)
foreach($feed->get_items($x, 1) as $item)
{
if($id == $dbid)
{
$x++;
$a=1; break;
}
else
{
}
} // end of foreach
} // end of for
The label gets replaced by a while and a self-fulfulling stop condition. And the goto becomes a break and resets the $a stop condition.
Something like this would probably work...
function loop(){
foreach($feed->get_items($x,1) as $item){
if($id==$dbid){
$x++;
loop();
}else{
}
}
}
for($i=0;$i<30;$++){
$x=0;
loop();
}
I'm sorry, I removed all the comments, they were annoying.
Move the declaration of $x outside of the for loop and replace your label/goto combination with a break, like so...
$x=0;
for($i=0;$i<30;$++) //print 30 articles
{
foreach($feed->get_items($x,1) as $item)
{
// create a unique id for the article of the feed
if($id==$dbid)
{
//if this id exists in the db,take the next article of the same feed which is not in the db
$x++;
continue;
}
else
{
//print the original article you grabbed
}
} // end of foreach
}//end of for
Agree with unset - using break will break if loop and keep iterating through for loop
Related
I have a foreach loop and an if statement. If a match is found i need to ultimately break out of the foreach.
foreach ($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ($current_device[0] == $device) {
// Found a match in the file.
$nodeid = $equip->id;
<break out of if and foreach here>
}
}
if is not a loop structure, so you cannot "break out of it".
You can, however, break out of the foreach by simply calling break. In your example it has the desired effect:
$device = "wanted";
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
// will leave the foreach loop immediately and also the if statement
break;
some_function(); // never reached!
}
another_function(); // not executed after match/break
}
Just for completeness for others who stumble upon this question looking for an answer..
break takes an optional argument, which defines how many loop structures it should break. Example:
foreach (['1','2','3'] as $a) {
echo "$a ";
foreach (['3','2','1'] as $b) {
echo "$b ";
if ($a == $b) {
break 2; // this will break both foreach loops
}
}
echo ". "; // never reached!
}
echo "!";
Resulting output:
1 3 2 1 !
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
break;
}
}
Simply use break. That will do it.
A safer way to approach breaking a foreach or while loop in PHP is to nest an incrementing counter variable and if conditional inside of the original loop. This gives you tighter control than break; which can cause havoc elsewhere on a complicated page.
Example:
// Setup a counter
$ImageCounter = 0;
// Increment through repeater fields
while ( condition ):
$ImageCounter++;
// Only print the first while instance
if ($ImageCounter == 1) {
echo 'It worked just once';
}
// Close while statement
endwhile;
For those of you landing here but searching how to break out of a loop that contains an include statement use return instead of break or continue.
<?php
for ($i=0; $i < 100; $i++) {
if (i%2 == 0) {
include(do_this_for_even.php);
}
else {
include(do_this_for_odd.php);
}
}
?>
If you want to break when being inside do_this_for_even.php you need to use return. Using break or continue will return this error: Cannot break/continue 1 level. I found more details here
I been trying to parse statements/questions from a forum site using a DOM parser.
Its working fine, it extracts all statements in the forum. So, i tried to put a limit of extracting statements using a if condition. it still doesn't fix the problem.
I thought the problem in structuring the if condition, so i ran the loop separately and it worked..
the code goes as follows:
<?php
$i = 1;
$elementCount=0;
while(true){
require_once('dom/simple_html_dom.php');
$html = file_get_html('http://www.usmleforum.com/forum/index.php?forum=1&Page='.$i);
foreach ($html->find("tr") as $row) {
$element = $row->find('td.FootNotes2',0);
if ($element == null) { continue; }
$textNode = array_filter($element->nodes, function ($n) {
return $n->nodetype == 3; //Text node type, like in jQuery
});
if (!empty($textNode)) {
$text = current($textNode);
echo $text."<br>";
$elementCount++;
}
}
if($elementCount==12){
break;
}
$i++;
}
?>
So, even after adding the if condition for 12 statements it still runs for forever.
now the if condition alone:
<?php
$i = 1;
$elementCount=0;
while(true){
echo "harish".$i."<br>";
$elementCount++;
if($elementCount==12){
break;
}
$i++;
}
?>
It works fine, prints only 12 given statement.
Any help is appreciated...
I'm not sure you are incrementing the $elementCount correctly but since I cannot see the output of your code I'm not sure.
I would move the break statement before the $elementCount++ and also echo the $elementCount to figure out what's really going on.
The resulting code would be like this:
<?php
$i = 1;
$elementCount=0;
while(true){
require_once('dom/simple_html_dom.php');
$html = file_get_html('http://www.usmleforum.com/forum/index.php?forum=1&Page='.$i);
foreach ($html->find("tr") as $row) {
$element = $row->find('td.FootNotes2',0);
if ($element == null) { continue; }
$textNode = array_filter($element->nodes, function ($n) {
return $n->nodetype == 3; //Text node type, like in jQuery
});
if (!empty($textNode)) {
$text = current($textNode);
echo $text."<br>";
echo $elementCount;
if($elementCount===12){
break;
}
$elementCount++;
}
}
$i++;
}
?>
You should better structure your code. So you would see that you increment the elementCount inside the foreach.
As you are checking outside of the foreach for the exact elementCount it can happen, that your counter rises above 12 elements and now will run forever.
You could just change the loop to
while($elementCount < 12) {...}
So you are checking if you have less than 12 and not exactly 12 or to:
if ($elementCount >= 12) {...}
I can't figure out how to test if there's a next item in my array by using the key to test against. I think this is better explained in code. I know there's an easier way, I'm just a noob!
Basically I want to know if there is another item in the array and if so get the ->comp_id value.
for($i=0; $i<count($allcomps); $i++)
{
if($allcomps[$i]->comp_id == $curCompID)
{
$currentIndex = $i;
if($allcomps[$i+1]->comp_id == null )
{
echo "there isn't a next";
}
//echo $allcomps[$currentIndex+1]->comp_id;
}
}
You're already looping through allcomps, so why do you need a check for the next one?
Why not check within the loop?
for($i=0; $i<count($allcomps); $i++) {
if (isset($allcomps[$i]->comp_id) and $allcomps[$i]->comp_id == $curCompID) {
$currentIndex = $i;
}
}
I think a foreach might be even easier:
foreach($allcomps as $i=>$comp) {
if (isset($comp->comp_id) and $comp->comp_id == $curCompID) {
$currentIndex = $i;
}
}
I'm using json_decode to parse JSON files. In a for loop, I attempt to capture specific cases in the JSON in which one element or another exist. I've implemented a function that seems to fit my needs, but I find that I need to use two for loops to get it to catch both of my cases.
I would rather use a single loop, if that's possible, but I'm stuck on how to get both cases caught in a single pass. Here's a mockup of what I would like the result to look like:
<?php
function extract($thisfile){
$test = implode("", file($thisfile));
$obj = json_decode($test, true);
for ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) {
//this is sometimes found 2nd
if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring1") {
}
//this is sometimes found 1st
if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring2") {
}
}
}
?>
Can anyone tell me how I could catch both cases outlined above within a single iteration?
I clearly could not do something like
if ($obj['patcher']['boxes'][$i]['box']['name'] == "string1" && $obj['patcher']['boxes'][$i]['box']['name'] == "string2") {}
...because that condition would never be met.
Generally what I do when I have raw data that is in an order that isn't ideal to work with is to run a first loop pass to generate a a list of indexes for me to pass through a second time.
So a quick example from your code:
<?php
function extract($thisfile){
$test = implode("", file($thisfile));
$obj = json_decode($test, true);
$index_mystring2 = array(); //Your list of indexes for the second condition
//1st loop.
$box_name;
for ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) {
$box_name = $obj['patcher']['boxes'][$i]['box']['name'];
if ( $box_name == "mystring1") {
//Do your code here for condition 1
}
if ($box_name == "mystring2") {
//We push the index onto an array for a later loop.
array_push($index_mystring2, $i);
}
}
//2nd loop
for($j=0; $j<=sizeof($index_mystring2); $j++) {
//Your code here. do note that $obj['patcher']['boxes'][$j]
// will refer you to the data in your decoded json tree
}
}
?>
Granted you can do this in more generic ways so it's cleaner (ie, generate both the first and second conditions into indexes) but i think you get the idea :)
I found that something like what #Jon had mentioned is probably the best way to attack this problem, for me at least:
<?php
function extract($thisfile){
$test = implode("", file($thisfile));
$obj = json_decode($test, true);
$found1 = $found2 = false;
for ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) {
//this is sometimes found 2nd
if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring1") {
$found1 = true;
}
//this is sometimes found 1st
if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring2") {
$found2 = true;
}
if ($found1 && $found2){
break;
}
}
}
?>
I have a foreach loop and an if statement. If a match is found i need to ultimately break out of the foreach.
foreach ($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ($current_device[0] == $device) {
// Found a match in the file.
$nodeid = $equip->id;
<break out of if and foreach here>
}
}
if is not a loop structure, so you cannot "break out of it".
You can, however, break out of the foreach by simply calling break. In your example it has the desired effect:
$device = "wanted";
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
// will leave the foreach loop immediately and also the if statement
break;
some_function(); // never reached!
}
another_function(); // not executed after match/break
}
Just for completeness for others who stumble upon this question looking for an answer..
break takes an optional argument, which defines how many loop structures it should break. Example:
foreach (['1','2','3'] as $a) {
echo "$a ";
foreach (['3','2','1'] as $b) {
echo "$b ";
if ($a == $b) {
break 2; // this will break both foreach loops
}
}
echo ". "; // never reached!
}
echo "!";
Resulting output:
1 3 2 1 !
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
break;
}
}
Simply use break. That will do it.
A safer way to approach breaking a foreach or while loop in PHP is to nest an incrementing counter variable and if conditional inside of the original loop. This gives you tighter control than break; which can cause havoc elsewhere on a complicated page.
Example:
// Setup a counter
$ImageCounter = 0;
// Increment through repeater fields
while ( condition ):
$ImageCounter++;
// Only print the first while instance
if ($ImageCounter == 1) {
echo 'It worked just once';
}
// Close while statement
endwhile;
For those of you landing here but searching how to break out of a loop that contains an include statement use return instead of break or continue.
<?php
for ($i=0; $i < 100; $i++) {
if (i%2 == 0) {
include(do_this_for_even.php);
}
else {
include(do_this_for_odd.php);
}
}
?>
If you want to break when being inside do_this_for_even.php you need to use return. Using break or continue will return this error: Cannot break/continue 1 level. I found more details here