STDIN and STDOUT in PHP


Well, I think PHP is great, but apparently somebody thinks that it is replacble in most cases if it is not with MySQL

lang STDIN and STDOUT in PHP beginner codeforces implementation php programming languages technical

Many online judges support PHP submissions. For example, the codeforces and the interviewstreet, they both support submissions of PHP code reading from STDIN and writing to STDOUT. Well, it is very simple. STDIN can be treated as a special file, named “php://stdin“. Similarly, the STDOUT can be opened by file “php://stdout“. So, the following illustrates opening from stdin and writing to stdout using file functions fscanf and fprintf respectively.

1
2
3
4
5
6
7
8
  $fr = fopen("php://stdin", "r");
  $fw = fopen("php://stdout", "w");
 
  fscanf($fr, "%d", $d);
  fprintf($fw, "%d", $d);
 
  fclose($fr);
  fclose($fw);
  $fr = fopen("php://stdin", "r");
  $fw = fopen("php://stdout", "w");

  fscanf($fr, "%d", $d);
  fprintf($fw, "%d", $d);

  fclose($fr);
  fclose($fw);

Ok, so we can try our first submission on online judge. We pick the easiest problem first here https://helloacm.com/a-super-agent/

We transform the python solution quickly into the PHP one, as presented below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  $fr = fopen("php://stdin", "r");
  $fw = fopen("php://stdout", "w");
 
  fscanf($fr, "%s", $r1);
  fscanf($fr, "%s", $r2);
  fscanf($fr, "%s", $r3);   
 
  function chk()
  {
    global $r1, $r2, $r3;
    return ($r1[0] == $r3[2]) &&
           ($r1[1] == $r3[1]) &&
           ($r1[2] == $r3[0]) &&
           ($r2[0] == $r2[2]);
  }
 
  if (chk())
  {
    fprintf($fw, "YES");
  }
  else
  {
    fprintf($fw, "NO");
  }
 
  fclose($fr);
  fclose($fw);
  $fr = fopen("php://stdin", "r");
  $fw = fopen("php://stdout", "w");

  fscanf($fr, "%s", $r1);
  fscanf($fr, "%s", $r2);
  fscanf($fr, "%s", $r3);   

  function chk()
  {
    global $r1, $r2, $r3;
    return ($r1[0] == $r3[2]) &&
           ($r1[1] == $r3[1]) &&
           ($r1[2] == $r3[0]) &&
           ($r2[0] == $r2[2]);
  }

  if (chk())
  {
    fprintf($fw, "YES");
  }
  else
  {
    fprintf($fw, "NO");
  }

  fclose($fr);
  fclose($fw);

Now, we have a quick comparison.
PHP Accepted 50 ms 6900 KB
Python Accepted 60 ms 2800 KB

The timing may not prove anything because the problem is not complex at all and there will be slight time variation between same submission.
However, the PHP seems using way too much memory (more than doubled) than python.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
349 words
Last Post: Codeforces: B. Taxi
Next Post: Codeforces: A. Double Cola

The Permanent URL is: STDIN and STDOUT in PHP

One Response

Leave a Reply