views:

169

answers:

6

Hi, I'm building some simple validation rules in php and my IDE (phped) is complaining about the syntax.

Can anyone tell me what is wrong with the following?

function notBlank($str) {
    (strlen($str) == 0) ? return false : return true;
}

phped complains of 'unexpected return'

Any advice appreciated.

Thanks.

+12  A: 

write it like this:

function notBlank($str){
   return strlen($str) != 0;
}
GSto
+2  A: 

Write it like this:

function notBlank($str) {
    return ( strlen($str) == 0 ? false : true );
}
Jan Hančič
No need for ternary operator here.
Josh Leitzel
You can remove the false or true, since the operator returns a boolean.
Garrett
off course, this is just my style of coding ...
Jan Hančič
A: 

try

return !!strlen($str);
Etan
+1  A: 

You cant use return within ternary operators. If you want to keep that syntax you have to do something like this:

function notBlank($str = '') {
    $var = (strlen($str) == 0) ? false : true;
    return $var;
}

Nevertheless do notice that the default way of doing things is more legible:

function notBlank($str = '') {
    if(strlen($str) == 0)
        return false;
    else
        return true;
}

Hope it helps!

Frankie
Can't say that I like the "if(x) return false else return true" type construction, when you could just use "return !x". Nevertheless, this gets +1 for actually answering the original question of what was wrong with query (rather than just explaining a different way to do it.)
Beska
A: 

strlen() returns 0 when the string is empty, and in PHP 0==false. So really, it's unnecessary to wrap strlen() in a function. If you want to insist on a boolean answer then cast it. ie:

(bool) strlen($string);

So instead of your function, which is assumably called in an if block, you'd just have

if(strlen($string)) //etc.
dnagirl
you may still want to wrap it in a function to make your code easier to understand. Who's to say the definition of "blank" won't change in the future? Your code is better able to handle changes like that if it's wrapped in a function, because it's more abstracted.
rmeador
@rmeador: to me this sounds like just-in-case programming. I'd agree that if I were planning on eventually implementing a more complex conditional, creating a function would be appropriate. But if I didn't have that intention I would not want to slow down simple function calls by wrapping them.
dnagirl
+1  A: 

GSto's answer seems the best here, though you might also like to check out php's empty function:

http://www.php.net/empty

PeterJCLaw