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
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...

 

 

 

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.