Search code examples
phpforeachfwriteord

PHP Loop With Fwrite() and Writing to a File


I already have a loop that prints "mason is spelled m a s o n" to a text file called results.txt.

Now I'm working on getting a loop to print "Decimal representation of m is 109 Binary representation of m is 1101101 Hexadecimal representation of m is 6d Octal representation of m is 155" for each letter in the name. I've figured this part out but I need to make a loop that goes through it for each letter in the name, and then writes the representation to results.txt.

I think I'll need to use a foreach loop similar to the one I used for the first fwrite statement. I cannot figure out how to set it up though. Here is what I have so far:

<?php
$name = "mason";
$nameLetterArray = str_split($name);

$results = fopen("results.txt", "w");

$output = " ";

foreach ($nameLetterArray as $nameLetter) {
$output .= $nameLetter." ";
}

fwrite($results, $name." is spelt ".$output);
fclose($results);

//here is what i need the loop to do for each letter in the name and save to 
//.txt file
$format = "Decimal representation of $nameLetterArray[0] is %d";
echo sprintf($format, ord($nameLetterArray[0]));
echo "<br>";
$format = "Binary representation of $nameLetterArray[0] is %b";
echo sprintf($format, ord($nameLetterArray[0]));
echo "<br>";
$format = "Hexadecimal representation of $nameLetterArray[0] is %x";
echo sprintf($format, ord($nameLetterArray[0]));
echo "<br>";
$format = "Octal representation of $nameLetterArray[0] is %o";
echo sprintf($format, ord($nameLetterArray[0]));
echo "<br>";

?>

Solution

  • If you want it after the m a s o n you can write another loop this way:

    <?php
    $name = "mason";
    $nameLetterArray = str_split($name);
    
    $results = fopen("results.txt", "w");
    
    $output = " ";
    
    foreach ($nameLetterArray as $nameLetter) {
    $output .= $nameLetter." ";
    }
    
    foreach($nameLetterArray as $nameLetter){
    
        $format = "Decimal representation of $nameLetter is %d";
        $output.="\n\n".sprintf($format, ord($nameLetter));
    
        $format = "Binary representation of $nameLetter is %b";
        $output.="\n\n".sprintf($format, ord($nameLetter));
    
        $format = "Hexadecimal representation of $nameLetter is %x";
        $output.="\n\n".sprintf($format, ord($nameLetter));
    
        $format = "Octal representation of $nameLetter is %o";
        $output.="\n\n".sprintf($format, ord($nameLetter));
    
    }
    
    
    //then write the result into the file
    
    fwrite($results, $name." is spelt ".$output);
    fclose($results);
    
    //if you want to see the output in the browser replace the \n by <br>
    $output=str_replace("\n","<br>",$output);
    echo $output;
    
    ?>
    

    I tried this and it works. please read even comments inside the code