Question

I have this function:

function permGen($a,$b,$c,$d,$e,$f,$g) {
    foreach ($a as $key1 => $value1){
        foreach($b as $key2 => $value2){
            foreach($c as $key3 => $value3) {
            print trim($d[rand(0,count($d)-1)]).trim($value1).trim($e[rand(0,count($e)-1)]).trim($value2).trim($f[rand(0,count($f)-1)]).trim($value3).$g;
            }
        }
    }
}

THIS IS the output that I need and it works perfectly when I'm printing on screen.

Assuming, I define all arguments without any problems. Now here is the problem, when I put permGen($arguments....); it works. But when I try and write this in a file by file handling like this,

$handle = fopen('new.txt', 'w+');
fwrite($handle, permGen($arguments...));

It doesnt seem to work. It creates a file but with nothing in it. I tried replacing print with return. Then it just gave 1 loop in new.txt and nothing else.Nothing seems to work as per what I want to get as my output.

Thanks

Was it helpful?

Solution

function permGen($handle, $a,$b,$c,$d,$e,$f,$g) {
    foreach ($a as $key1 => $value1){
        foreach($b as $key2 => $value2){
            foreach($c as $key3 => $value3) {
                fwrite(
                    $handle, 
                    trim($d[rand(0,count($d)-1)]).trim($value1).trim($e[rand(0,count($e)-1)]).trim($value2).trim($f[rand(0,count($f)-1)]).trim($value3).$g;
                );
            }
        }
    }
}

// To write to a file
$handle = fopen('new.txt', 'w+');
permGen($handle, $other, $arguments, ...);
fclose($handle);

// To write to normal output (browser, whatever)
$handle = fopen('php://output', 'w');
permGen($handle, $other, $arguments, ...);
fclose($handle);

EDIT

If you don't want to modify your function in any way, then you can use output buffering to capture the printed output:

ob_start();
permGen($arguments...);
$output = ob_get_contents();
ob_end_clean();

file_put_contents(
    'new.txt',
    $output,
    FILE_APPEND
);

OTHER TIPS

function permGen($a,$b,$c,$d,$e,$f,$g) {
    $output = '';
    foreach ($a as $key1 => $value1){
        foreach($b as $key2 => $value2){
            foreach($c as $key3 => $value3) {
                $output .= trim($d[rand(0,count($d)-1)]).trim($value1).trim($e[rand(0,count($e)-1)]).trim($value2).trim($f[rand(0,count($f)-1)]).trim($value3).$g;
            }
        }
    }

    return $output;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top