Irfan Mir
Irfan Mir

Reputation: 2175

recursive function not executing code second call and onwards

So I have an array of documents to add each a string as an element in an array and an instance of a class that has a private member function add document, which essentially adds the document to a new array of added documents. The function don() takes on 3 arguments, the string it needs to add to the array of added documents, instance of the class to add the document from inside the function, and an array of more content to add.

In psuedo code it goes something like this:

$contentsAdded = []; //blank array
$contents = ['document one text', 'document two text', 'document three text';
$firstDoc = 'hello I am the first document';

function don($currentString, $instance, $contentArray){
    //addDocument() adds strings to  /         //$contentsAdded
    $instance->addDocument($currentString);
    //Travel through array $contentArray
    //if $contentArray[iterator] is not in     //$contentsAdded, then
    don($contentArray[i], $instance, $contentArray);
}
don($firstDoc, $instance, $contents);

What is the best way to do this?

Especially if when I did it the way I figured, $contentsAdded only has $firstDoc in it?

Upvotes: 0

Views: 52

Answers (1)

MatRt
MatRt

Reputation: 3534

You don't need to separate the first document from the other, as you have to make a generic process. And there is no need to make a recursive fonction in this case (recursive function will potentially take more resources, use it with caution).

You should simply iterate over your document array, and add them, one by one, using your instance object.

// Initialize the list of document to add
$contents = array('first document',
                  'document one text',
                  'document two text',
                  'document three text');

// Loop over your array of document
foreach($contents as $oneDocument)
    $instance->addDocument($oneDocument);

Upvotes: 1

Related Questions