Search code examples
phpxamppfopenfwrite

PHP - How to write the result of a for loop to a file


I am trying to have a for loop run through each part of my array and print out a message saying "mason is spelled m a s o n". I understand how to write to a file and I understand using a for loop to print out each element in the array, but I do not understand how to get the data from the for loop output into a variable that I can put in my fwrite function. Here is what I have so far:

<?php
$name = "mason";
$nameLetterArray = str_split($name);
$results = fopen("results.txt", "w");
fwrite($results, $forLoopOutput); //here forLoopOutput would be the "m a s o n" part
fclose($results);

$length = count($nameLetterArray);
for ($i = 0; $i < $length; $i++) {
print $nameLetterArray[$i];
}

Solution

  • As you've already virtually written the code, there are only a few changes to make...

    $name = "mason";
    $nameLetterArray = str_split($name);
    $results = fopen("results.txt", "w");
    // Create output string to save multiple writes
    $output = "";
    $length = count($nameLetterArray);
    for ($i = 0; $i < $length; $i++) {
         //print $nameLetterArray[$i];
        $output .= $nameLetterArray[$i]." ";  // Add letter followed by a space
    }
    // Write output
    fwrite($results, $name." is spelt ".$output); 
    // Close file
    fclose($results);
    

    You could also use a foreach() in the loop instead

    $name = "mason";
    $nameLetterArray = str_split($name);
    $results = fopen("results.txt", "w");
    fwrite($results, $name." is spelt "); 
    // Create output string to save multiple writes
    $output = "";
    foreach ($nameLetterArray as $nameLetter) {
         //print $nameLetterArray[$i];
        $output .= $nameLetter." ";  // Add letter followed by a space
    }
    // Write output
    fwrite($results, $name." is spelt ".$output); 
    // Close file
    fclose($results);
    

    Or (finally) you could use implode() instead of the loop...

    $output = implode(" ", $nameLetterArray);