0

I want if value field txtname was empty echo It is ok but it don't work in my code(if field was empty and click on button you see output with print_r(...)), Please see my demo and my code. what do I do?

Demo: http://codepad.viper-7.com/FNWcIs

<form method="post">
    <input name="txtname[]">
    <button>Click Me</button>
</form>
<?php
    if ($_POST) {
        $txtname = $_POST['txtname'];
        if (!empty($txtname)) {
            echo '<pre>';
            print_r($txtname); // Output this is: Array ( [0] => )
        } else {
            echo 'it is ok';
        }
    } 
?>
2
  • 1
    try var_dump($_POST) what do you get there? Commented Nov 5, 2011 at 9:45
  • @ Truth - See here: codepad.viper-7.com/UXe1ZC and click on button Click Me Commented Nov 5, 2011 at 10:35

3 Answers 3

2

$txtname or ($_POST['txtname']) is an array with one element. Even that element is empty, empty() returns TRUE for any array that has one or more elements.

That should explain the behavior of your code.

To achieve what you're looking for, change the HTML:

From:

<input name="txtname[]">

To:

<input name="txtname">

If you don't use the brackets, it will be a string. And empty will return FALSE if it is empty. See Variables From External Sources PHP Manual.

Sign up to request clarification or add additional context in comments.

Comments

2

change input field name to txtname like show below.

<input name="txtname">

Or if you want to use array of textboxes try below code.

<form method="post">
    <input name="txtname[]">
    <input name="txtname[]">
    <input name="txtname[]">
    <button>Click Me</button>
</form>
<?php
    if($_POST){
        $txtname       = $_POST['txtname'];

            foreach($txtname   as $key=>$value)
            {
                if(!empty($value)){
                    echo '<br>'.$value; // Output this is: Array ( [0] => )
                }else{
                    echo '<br>it is ok';
                }
            }
    }
?>

Comments

1

You can try it this way it works if you are not intending to pass one value to the variable $txtname

`

    $txtname       = $_POST['txtname'];
    if($txtname[0]){
        echo '<pre>';
                print_r($txtname); // Output this is: Array ( [0] => )
            }else{
                echo 'it is ok';
            }
}

?>`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.