Jump to content

value as 0 treated as empty string


sandy1028

Recommended Posts

If the value of $keyword is empty, only then it should print "Hi". else if should print "Hello".

 

Problem is sometimes the value $keyword will be "0". How to handle this condition

 

$keyword=0;
//$keyword='abc';

        if (empty($keyword)) {
            echo 'Hi';
        } else {
            echo "Hello";
        }

Link to comment
https://forums.phpfreaks.com/topic/260857-value-as-0-treated-as-empty-string/
Share on other sites

Read documentation/api about the function empty.

 

You could do this instead:

if($keyword==''){

}

 

But I guess you might want the functionality of !isset as well?

 

        if (empty($keyword) && $keyword !== 0 ) {

^ This won't work if you for example do this:

$keyword = 0.0;

This seems to do exactly what you want... or at least I think so! o.o'

if(!isset($keyword) || $keyword == '')

and so does the code I posted.... :shrug:

No, your checked for type as well, and if it's a float zero then it won't equal integer zero.

I guess you wrote !== to avoid this problem:

<?php

$keyword = false;

if($keyword == 0){
echo 'false == 0';
}

?>

 

Let me show you what I mean:

 

<?php

$keyword = 0.0;

if(empty($keyword) && $keyword!==0 ){
echo $keyword.' = empty!';
}

?>

Try to run that, and you will see what I mean.

It will return: 0 = empty!

 

But you are right, mine is wrong as well. I would have played around with it for a bit more, but I don't have the time at the moment.

 

Thanks All.

 

How about using this ?

 

if (strlen($keyword) >= 1) {

 

which is better option. Please suggest.

Sure you can do that, but it won't check if the $keyword is not set, and neither if it's set to true or false.

I used !== because it fit for the value that was requested for the check, the OP said 0 not 0.0 or 0.00000 or 000000.000000000000000

 

the issue being that PHP is a loose langauge, so 0 vlaues are parsed as false and false is parsed as empty. 

 

another way you could work it would be (assuming the normal kwywords are actualy words):

<?php
     
$keyword = (string)0.0;

if(empty($keyword) && $keyword != '0'){
echo $keyword.' is empty!';
}
echo $keyword;

?>

or how about

<?php
     
$keyword = (string)0.0;

if(empty($keyword) && $keyword != chr(48)){
echo $keyword.' is empty!';
}
echo $keyword;

?>

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.