Veltar
Veltar

Reputation: 741

$_post['value'] exists but when I check it with empty it returns false

I have a post-variable that has to be checked whether it is empty or not. I look at the value of the variable like this:

print_r($_POST['arrayId']);

and it prints the expected value. However if I do this:

if(!empty($_POST['arrayId'])) {
    // some stuff
} else {
    echo "f";
}

f is printed, and the code that should be executed isn't. How is this possible?

Upvotes: 0

Views: 95

Answers (3)

Andreas Linden
Andreas Linden

Reputation: 12721

do this instead, it will check if the key is present in the post array, regardless of the value. also works for NULL, false, 0 and any other values which are treated as "empty" values...

if(array_key_exists('arrayId', $_POST)) {
    // some stuff
} else {
    echo "f";
}

Upvotes: 3

Mihai Iorga
Mihai Iorga

Reputation: 39704

empty() returns true if value is 0.

change with:

if(isset($_POST['arrayId']) && strlen($_POST['arrayId'])) {
    // some stuff
} else {
    echo "f";
}

Upvotes: 1

Ashish Kasma
Ashish Kasma

Reputation: 3642

Verify input'$var' to empty() function

empty($var)

Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.

The following things are considered to be empty:

"" (an empty string) 0 (0 as an integer) 0.0 (0 as a float) "0" (0 as a string) NULL FALSE array() (an empty array) $var; (a variable declared, but without a value)

http://php.net/manual/en/function.empty.php

Upvotes: -1

Related Questions