English Name Full Spelling Random Numbering Script Realized by PHP

  • 2021-07-07 06:33:33
  • OfStack

Requirements:
1. After executing the script, the students who want to go enter the English name and spell it all, resulting in random numbers between 01 and 99.
The larger the number, the more you will participate in the project practice. The number you have caught before cannot appear the same number next time.
2. After the first name is entered, the screen outputs information and records the name and number to the file. The program cannot exit
Continue to wait for other students to enter.

Implementation code (please execute on the command line, not in WEB environment):


<?php

//  Number base 
$num = range(1, 99);

//  Random disruption 
shuffle($num);

$filename = './user.txt';

//  Open Log File 
$handle = fopen($filename, 'w');

//  Sort list of users 
$user = array();

while (true) {
 echo "\r\nEnter your name:";

 $content = read();

 // exit  Exit script 
 if ($content == 'exit') {
  break;
 }

 //  Take out random values 
 $n = array_pop($num);

 //  Write to a file 
 fwrite($handle, $n.' '.$content."\r\n");

 $user[$n] = $content;

 //  Output to console 
 echo "Hi $content, your number is " . $n."\r\n";
}

//  Turn off control to input stream 
fclose($GLOBALS['StdinPointer']);

fwrite($handle, "\r\n");
fwrite($handle, '---------------- Gorgeous dividing line -----------------');
fwrite($handle, "\r\n");

ksort($user);

foreach ($user as $k=>$v) {
 fwrite($handle, $k.' '.$v."\r\n");
}

//  Close a file 
fclose($handle);


/**
*  Get command-line input values 
* @param string $length
* @return string
*/
function read($length='255'){
 if (!isset($GLOBALS['StdinPointer'])){
  $GLOBALS['StdinPointer']=fopen("php://stdin","r");
 }
 $line=fgets($GLOBALS['StdinPointer'],$length);
 return trim($line);
}


Related articles: