Run
Run

Reputation: 57176

PHP empty: take a single 0 as a string only?

I want to take a single0 as a string only for db injection but not 00 or 0000 as string.

$post["content"] = '00';

if (empty($post["content"]) && $post["content"] !== '0') 
{
     echo "this field must not be empty!";
}

It does not return it as an error.

What should I do?

Upvotes: 1

Views: 69

Answers (2)

BlitZ
BlitZ

Reputation: 12168

Use !trim() instead:

<?php
$post["content"] = '00';


if ($post["content"] !== '0' && !trim($post["content"], '0')) 
{
    echo "this field must not be empty!";
}
?>

Upvotes: 1

Sven
Sven

Reputation: 70863

Your test is wrong.

$single ="0";
$double = "00";

var_dump(empty($single)); // true
var_dump(empty($double)); // false

Double zeros are not empty.

Do not use empty() for validation. Do you know from the top of your head which values are considered "empty"? There are some surprises, and that is reason enough for me to avoid that function.

Upvotes: 0

Related Questions