PHP $ _POST错误

I'm getting the following error with $_POST['str']:

Notice: Undefined index: str in C:\Program Files\EasyPHP-5.3.8.0\www\strrev.php on line 12

I spent too much time to find an answer for this but no luck! Please take a look at the code and let me know what's wrong with it?

<html>
<head>
<title></title>
</head>
<body>
  <?php 
    if (trim($_POST['str'])) {
      $str = $_POST['str'];
  $len = strlen($str);
      for($i=($len-1); $i>=0;$i--) {
      echo $str[$i];
      } 
} else {
  ?>
<form method="post" action="">
    <input type="text" name="str" />
    <input type="button" name="submit" value="Reverse" />
    </form>
    <?php
  }
  ?>
</body>
</html>

It shows the text field and Reverse button beside the error. And also when I push the button nothing will happens.

Change if (trim($_POST['str'])) to if (!empty($_POST['str']))

Your if statement is trying to trim an array index that does not exist, hence the error. You must check if your index exists first.

In case anyone is wondering - I used empty instead of isset as the OP, by using trim, implied (or at least, I inferred from this) that a properly set $_POST['str'] containing an empty string was unacceptable. This won't fix the case where $_POST['str'] contains a bunch of spaces, however.

You're not checking if a POST has actually occured:

<html>
...
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   if ($_POST yada yada yada) {
       ...
   }
}
?>

<form action="" method="POST">
...
</form>

...

</html>

$str is not necessarily an array. In order to loop through it, it needs to be an array. It's just copying that value from $_POST['str'], so when you do the post either

Make sure it's an array with

if (is_array($str))