Jump to content

case statement failing.


stockton

Recommended Posts

Please tell me what stupid mistake I have made in the following code.

<?php
$operator = fgets(STDIN);
$operator = $operator[0];
echo "\n".$operator."\n";
switch ($operator) {
case '+':
   echo "Plus";
   break;
case '-':
   echo "Minus";
   break;
}
?>

 

The switch never finds a case for either operator. Why?

Link to comment
https://forums.phpfreaks.com/topic/191053-case-statement-failing/
Share on other sites

However if the user types the + or - on the keyboard it fails.

macbookpro:~ phptest$ php test.php 
+

+
Plus
macbookpro:~ phptest$ php test.php 
-

-
Minus

 

sry but it works for me...even with STDIN ...

 

Have you other code in the script ? maybe there is the error...

 

 

 

 

However if the user types the + or - on the keyboard it fails.

 

<?php
$operator = fgets(STDIN);
echo var_dump ($operator) . "<br/>\n";
echo ord(trim($operator[0]));
?>

 

Please post the results of this.

What you are most likely getting is something encoded, or as mentioned an untrimmed character. This will verify it 'bit by bit' to prove your point.

The following now works but I don't understand what changed to make it work.

<?php
$operator = fgets(STDIN);
$operator = $operator[0];
echo var_dump ($operator) . "<br/>\n";
echo ord(trim($operator[0]));
// echo "\n".$operator."\n";
switch ($operator) {
case '+':
   echo "\nPlus\n";
   break;
case '-':
   echo "\nMinus\n";
   break;
}
?>

the result of the above is:-

php Switch.php
+
string(1) "+"
<br/>
43
Plus

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.