Jump to content

Break in a recursive function


ankme

Recommended Posts

I have a function that searches first for a line in a file and then for a string in that line. If the string is not found, it concatenates the line with the next line and so on until it finds the string.

The following script works but it is time consuming. I want to put a "break" somewhere so that if the line is found, the foreach will break. Can someone please help and tell me how to do this? If I put the break before

the recursive call, it wont do the call. If I put it after, it wont get to the break.

Thanks!

 

function findEndTag($file, $line, $consolidatedLine)

{

  $endTagFound = strstr($consolidatedLine,"/>");

  if (!$endTagFound)

  {

  $fileContent = file($file);

  foreach ($fileContent as $i => $lineArray)

  {

  if ($lineArray == $line)

  {

  $consolidatedLine = $consolidatedLine." ".$fileContent[$i+1];

 

  return (findEndTag($file, $fileContent[$i+1], $consolidatedLine));

 

  }

  }

}

  else

  {

  return $consolidatedLine;

  }

}

Link to comment
https://forums.phpfreaks.com/topic/236952-break-in-a-recursive-function/
Share on other sites

It seems like the logic behind the function should be modified. Instead of calling the function again to test the data you just read, why not test the data right away? Maybe switch it to:

 

<?php

function findEndTag($file, $line, $consolidatedLine) {
     $fileContent = file($file);
     foreach ($fileContent as $i => $lineArray) {
          if ($lineArray == $line) {
               $consolidatedLine = $consolidatedLine." ".$fileContent[$i+1];
               $endTagFound = strstr($consolidatedLine,"/>");
               if (!$endTagFound) {
                    return (findEndTag($file, $fileContent[$i+1], $consolidatedLine));
               } else {
                    return $consolidatedLine;
               }
          }
     }
}


?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.