Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get user input for switch statement in php?

Tags:

php

user-input

As questioned above I'm trying to get user input in my PHP script to do further tasks. Is there any method in PHP to get user input like 'scanf()' used in C

<?php
echo "Swapping Numbers </br> Please select the method: </br>";
echo "1. Using 3rd variable </br> 2. Using add/sub </br> 3. Using mul/div";
//read user input $choice
switch($choice)
{
case 1:
        break;
case 2:
    break;
case 3:
    break;
default:
        echo "</br>You entered wrong choice";
}
?>
like image 805
Vilas Avatar asked Feb 12 '26 07:02

Vilas


1 Answers

the STDIN constant is pre-defined and available for you to use immediately.

You can get user input using fgets and fscanf

<?php
$line = trim(fgets(STDIN));     // reads one line from STDIN
fscanf(STDIN, "%d\n", $number); // reads number from STDIN

For example

<?php
echo "Enter a number: ";
fscanf(STDIN, "%d\n", $number);
switch ($number) {
  case 1: echo "one\n"; break;
  case 2: echo "two\n"; break;
  case 3: echo "three\n"; break;
  default: echo "I can't count that high\n";
}

Check out the I/O docs for more detailed information

like image 124
Mulan Avatar answered Feb 14 '26 21:02

Mulan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!