Eric Favoni
Eric Favoni

Reputation: 183

PHP check array using empty() function

I'm newbie of PHP. I have this input for add pultiple array into MySQL database.

<input name="image_url[]" id="ads" type="text" value="">

now, I need to check if not empty value send to database.

I check with empty() function but this not worked with name="image_url[]".

HTML :

<input name="image_url[]" id="upload" type="text" value="">

PHP code:

if(empty($_POST['image_url'])){

echo 'true';

} else {

echo 'false';

}

But always I see output : true. in default my input is blank/empty.

I check and remove [] from input name(name="image_url") and I see true output.

I think my problem is input array name.

how do fix this and check for empty value?!

in var_dump($_POST) I see this output:

  ["image_url"]=>
  array(1) {
    [0]=>
    string(0) ""
  }

Live DEMO : http://madenade.besaba.com/php/?action=editnews&id=10

NOTE: check in demo with empty value and not empty value! u see output : false

Upvotes: 0

Views: 112

Answers (2)

rid
rid

Reputation: 63442

You're creating an array of values by using [] in the input name. If you only need one value, not more of them, then remove the [] in the input name, otherwise you'll get an array in $_POST['image_url'].

<input name="image_url" id="upload" type="text" value="">
if (empty($_POST['image_url'])) {
    echo 'true';
} else {
    echo 'false';
}

Otherwise, if you do need an array of values, then keeping [] in the input name means that $_POST['image_url'] will contain an array of values, not a single value. You probably want to check each one of them.

<input name="image_url[]" id="upload" type="text" value="">
foreach ($_POST['image_url'] as $image_url) {
    if (empty($image_url)) {
        echo 'true';
    } else {
        echo 'false';
    }
}

Upvotes: 1

vamsisnikky
vamsisnikky

Reputation: 11

First use Html Like This(If ur entering single Value)

<input name="image_url" id="upload" type="text" value="">

Then In PHP Code Check Like This

    if(isset($_POST['image_url']) && $_POST['image_url'] != ""){

echo 'true';

} else {

echo 'false';

}

this will give you required output

Upvotes: 0

Related Questions