Cyril Horad
Cyril Horad

Reputation: 1565

PHP function returning boolean

How can I have a boolean returning function?
I mean like this on other programming language.

return true; // return false

Upvotes: 8

Views: 82957

Answers (6)

Gleb Kemarsky
Gleb Kemarsky

Reputation: 10398

Since PHP 5.5 you can use the boolval function:

(PHP 5 >= 5.5.0, PHP 7) boolval — Get the boolean value of a variable

return boolval( $result );

Or just convert to boolean. But perhaps all this is not necessary:

To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.

return (bool) $result;
return (boolean) $result;

Upvotes: 0

EvilCoder
EvilCoder

Reputation: 1

I do understand the question, as in visual C# you can define a function to return bool only. This is not the case in PHP. You can just use function blabla($val) { return ($val == "yes" ? true : false); }. No support for "public bool($value) { return true; // false }"

Upvotes: -1

oopbase
oopbase

Reputation: 11385

<?php

  function doSomething() {
    return true;
  }

The function you need could look like this:

  function check($var, $length) { 
    return (strlen($var)<=$length) && (isset($var));
  }

?>

Upvotes: 5

BGPHiJACK
BGPHiJACK

Reputation: 1397

The question does not entirely make sense, because you have not asked something you've already solved.

The function in PHP can be done like this.

function check($int) {
   if ($int == 3) {
      return true;
   } else {
      return false;
   }
}
if (check(3)) echo "Returned true!";

Upvotes: 14

mario
mario

Reputation: 145482

As a more practical example, you can use any boolean expression as result:

return ($data != "expected") or ($param == 17);

Upvotes: 2

Mark Baker
Mark Baker

Reputation: 212412

Incredibly enough

return true;

e.g.

function testIfABC($x) {
    if ($x === 'ABC') {
        return true;
    }
    return false;
}

though that could more easily be written as:

function testIfABC($x) {
    return ($x === 'ABC');
}

which will still return a boolean value

Upvotes: 8

Related Questions