當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


PHP readline()用法及代碼示例


readline()function 是 PHP 中的內置函數,用於從命令行窗口讀取用戶輸入。它提供了一種交互式提示用戶輸入並將其響應捕獲為字符串的方法。

用法:

readline($prompt): string|false

參數:該函數接受一個參數,如下所述。

  • $prompt: 這是一個可選參數。這是用戶進入命令行接口時顯示的字符串參數。

返回值: readline()函數返回提供的字符串。如果沒有發現更多數據可讀取,該函數將返回 false。

程序1:下麵的程序演示了readline()函數。

PHP


<?php 
    
// Simple example prompting the user for their name 
$name = readline("Enter your name: "); 
  
// Check if the user provided a name 
if ($name !== "") { 
    echo "Hello, $name! Nice to meet you."; 
} else { 
    echo "You didn't enter your name."; 
} 
  
?>
輸出
Enter your name: Hello, ! Nice to meet you.

程序2:下麵的程序演示了readline()函數。

PHP


<?php 
    
// Function to ask a question and get user input 
function askQuestion($question) { 
    return readline($question . " "); 
} 
  
// Main program 
echo "Welcome to the Interactive Survey!\n"; 
echo "Please answer the following questions:\n"; 
  
// Ask the user some questions 
$name = askQuestion("1. What is your name?"); 
$age = askQuestion("2. How old are you?"); 
$location = askQuestion("3. Where are you from?"); 
$hobby = askQuestion("4. What is your favorite hobby?"); 
$feedback = askQuestion("5. How do you like this survey?"); 
  
// Display the survey results 
echo "\nSurvey Results:\n"; 
echo "Name: {$name}\n"; 
echo "Age: {$age}\n"; 
echo "Location: {$location}\n"; 
echo "Favorite Hobby: {$hobby}\n"; 
echo "Feedback: {$feedback}\n"; 
  
echo "\nThank you for participating in the survey!\n"; 
?>

輸出:

Welcome to the Interactive Survey!
Please answer the following questions:
1. What is your name? GFG
2. How old are you? 20
3. Where are you from? India
4. What is your favorite hobby? ID
5. How do you like this survey? bored
Survey Results:
Name: GFG
Age: 20
Location: India
Favorite Hobby: ID
Feedback: bored
Thank you for participating in the survey!

參考:https://www.php.net/manual/en/function.readline.php



相關用法


注:本文由純淨天空篩選整理自neeraj3304大神的英文原創作品 PHP readline() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。