0

My code is extremely simple, but I have no idea what I've done to cause this error.

Notice: Undefined index: value in C:\xampp\htdocs\index.php on line 8

<form name="shuffle" action="" method="POST">
    <input type="text" name="value">
    <input type="submit" value="Shuffle">
</form>

PHP code: echo str_shuffle($_POST['value']);

  • If the form is not submitted then you should get this error. Try `if(isset($_POST)){ echo str_shuffle($_POST['value']); }` – Think Different Jun 20 '14 at 12:13
  • possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – Gerald Schneider Jun 20 '14 at 12:14
  • the value will be posted only if the form is submitted.so untill it is submitted there is noting called 'value' and the error will be shown. – Sougata Bose Jun 20 '14 at 12:22

2 Answers2

3

You have posted form in same file. so you need to check if form is submitted or not.

Try like this:

 if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
    echo str_shuffle($_POST['value']);
    }
Awlad Liton
  • 9,366
  • 2
  • 27
  • 53
  • @Alanay : did you get the point? why it was happen? let me know if you need more explanation and do not forgot to mark it as accepted if it works :) – Awlad Liton Jun 20 '14 at 12:24
  • Yes I think I do, I'm just gonna have to try remembering the syntax for next time. Thank you again. –  Jun 20 '14 at 12:26
0

If you call $_POST['value'] when form has not been previously submitted you get a warning that the key of $_POST is not defined.

Try to define the variable anyway. So that if you have sent the form, take the value of the field, otherwise the value is FALSE

$value = isset($_POST['value']) ? $_POST['value'] : FALSE; //$value is always defined
if($value !== FALSE){
//something like
echo str_shuffle($value);
}

PHP isset function

Soanix
  • 36
  • 2