2

I have encountered a problem that I need to solve using PHP.

I have a multiline input that looks like this:

a,b,c,d
a=10 tools
b=50 subtools
c=80 othertools

I want to read input using stdin but I'm only able to read the first line. using fscanf(STDIN, "%s\n", $name);

How do I read the multiple input lines and save them to a list? I want to use a comma as separator for first-line and space as a separator for the rest.

Devarshi Goswami
  • 1,035
  • 4
  • 11
  • 26

1 Answers1

2

Using fgets you can do

$c = 0;
do {
    $f = fgets(STDIN);
    echo "line: $f";
    if ( $c == 0) {
        echo 'its a a,b,c,d type line' . PHP_EOL;
    } else {
        echo 'its a a=10 tools' . PHP_EOL;
    }
    $c++;
   
} while ($c < 5);
echo 'END';

Or

$c = 0;
while ($f = fgets(STDIN) !== FALSE and $c<4) {
    echo "line: $f";
    if ( $c == 0) {
        echo 'its a a,b,c,d type line' . PHP_EOL;
    } else {
        echo 'its a a=10 tools' . PHP_EOL;
    }
    $c++;   
}
echo 'END';
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149