phphtmlfilefile-handlingfilehandle

Php : Separate file content into different files


I have this file

1 + 3 = 4
0 + 0 = 0
1 + 2 = 3
1 / 1 = 1
2 * 3 = 6

I want to separate the (firstNum, secondNum, operationUsed(+,-,*,/), and result) into 4 different files


Solution

  • Don't know why you would ever need this but here you go

    <?php
    // read
    $array = file('original.txt');
    
    // parse
    $set = [
     'firstNum' => [],
     'secondNum' => [],
     'operationUsed' => [],
     'result' => [],
    ];
    foreach ($array as $value) {
        $value = explode(' ', $value);
        
        $set['firstNum'][] = $value[0];
        $set['secondNum'][] = $value[1];
        $set['operationUsed'][] = $value[2];
        $set['result'][] = $value[3];
    }
    
    // write
    file_put_contents('firstNum.txt', implode(PHP_EOL, $set['firstNum']));
    file_put_contents('secondNum.txt', implode(PHP_EOL, $set['secondNum']));
    file_put_contents('operationUsed.txt', implode(PHP_EOL, $set['operationUsed']));
    file_put_contents('result.txt', implode(PHP_EOL, $set['result']));