0

I need to write an if condition to detect blank string on PHP. But the variable may get numbers also. So I write the condition like follows. While the variable get the value zero "0" as number the condition detect it as blank ""

$string = array_search("value match", $array);   //$string = 0;

if($string == "")
{
    echo "not equal";
}

Is it a bug on PHP? How we can detect for blank value (not null) for a variable which may have numbers or string?

5
  • 5
    $string is not a string but an integer. And that 0 == "" is intended behavior. Commented Nov 30, 2014 at 18:19
  • Could try: if ($string != "" && $string != 0) { } // GOOD Commented Nov 30, 2014 at 18:19
  • For further detail following is the function used to get the value of variable $string = array_search("value match", $array);. If there is no search match i have to detect it by if condition. Commented Nov 30, 2014 at 18:29
  • 1
    Have you tried $string !== false ? Commented Nov 30, 2014 at 18:32
  • @SmokeyPHP: yes it works $string === false then how 0 escape from equal to false?. Any how your idea works for my requirement. Thank you. Commented Nov 30, 2014 at 18:35

2 Answers 2

4

Try this:

if ($string === "") { //With three equality signs
}

That's because both 0 and "" evaluates to empty(). It's not a bug, but a side effect of loose typing.

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

3 Comments

This fail to detect ""
How comes? It's a direct comparison to "" ("" === "" will return true, of course), how can it fail? It will not detect 0, however. For this, you have to use $string === 0 which will check, if $string is a number and exactly 0.
Following is the function i used to get value $string = array_search("value match", $array);. If there is no search match I have to detect it by if condition.
2

When using array_search you will need to check for false:

if($string !== false) //Note !== rather than != (stops 0 equating to false)

Otherwise 0 will be treated as 'falsy', even though it's a valid return value (first element/key)

1 Comment

This is correct I thing small modification needed to match the code in question like follows if($string === false). Thanks for the working solution and the proper explanation.

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.