I cannot get a false value to return here. A true value returns fine. What am I missing?
if ((count($this->_brokenRulesCollection)) == 0) {
return true;
} else {
return false;
}
In PHP, false when converted to a string is an empty string, and true converted to a string is "1".
Use var_dump instead of echo for debugging.
The code can just return false if the array $this->_brokenRulesCollection is not empty.
If $this->_brokenRulesCollection is not an array or an object with implemented Countable interface, then count($this->_brokenRulesCollection) will returned 1.
In conditional expressions (unless you use the type matching operators === or !==) any non-zero integer is equivalent to true, any non-zero length string is equivalent to true and conversely, zero or a blank string are false.
So
if ((count($this->_brokenRulesCollection)) == 0) {
return true;
} else {
return false;
}
Can be written as just:
return count($this->_brokenRulesCollection);
C.
if you actually want to see "false", put the value in a variable before you return. as such:
if ((count($this->_brokenRulesCollection)) == 0) {
$value=true;
} else {
$value=false;
}
return $value;
Related
I have a basic simple question. Consider the following code
function checkNumber($number)
{
if (is_numeric($number))
{
return true;
}
else
{
return false;
}
}
$isValidNumber = checkNumber(123);
Will isValidNumber variable contain a string of value true?
It will return a bool value. Can you check it by var_dump($isValidNumber).
Result is:
bool(true)
It will always be a boolean because even if you just return is_numeric($number) it will be a bool because the function itself returns a boolean like explained here.
Even if you made useless stuff like
function checkNumber($number)
{
return $is_numeric($number);
}
$isValidNumber = checkNumber(123);
$number will be always an boolean in your case.
function sample($number){
if ($number % 2 == 0){
echo "Even";
}else{
echo "Odd";
}
sample(3);
When I replace echo with return nothing happens? How do you know if it returns something?
The below sample is what concerns me. Thanks in advance!
function sample($number){
if ($number % 2 == 0){
return true;
}else{
return false;
}
sample(3);
Something definetly happens. You just aren't catching the result.
// Return true or false at random
function trueOrFalse()
{
return (rand(1, 10) > 5) ? true : false;
}
// Now we are going to check what is being returned
print_r(trueOrFalse()); // true
print_r(trueOrFalse()); // false
print_r(trueOrFalse()); // false
print_r(trueOrFalse()); // true
You can also use the return value in if statements and such:
if (trueOrFalse() == true) {
echo "It was true this time";
}
The PHP Manual tells us
Values are returned by using the optional return statement. Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called. See return for more information.
Additional reading
PHP Manual on return values
if (sample(3)) echo 'This is even';
else echo 'this is odd';
Manual and read about functions, returns, IF
When you return a boolean, it is either true or false. If you really want to output a boolean, you can try with var_dump :
var_dump(true);
will output yourfile.php:3:boolean true
and
var_dump(false);
will output yourfile.php:3:boolean false
Booleans are not made to be outputed but to check if a statement is true or false.
In your case, you want to know if a number is even, so the method could be named isEven and return true if the number is even.
Then you could use it like :
<tr class="<?= isEven($i) ? 'even' : 'odd' ?>">
Or
if (isEven($i)) {
...
}
Why does it not work to use an if statement to determine if a function should return true or false? True works, but false doesn't.
Here is my code:
function test($var){
if($var == "string"){
return true;
}else{
return false;
}
}
Doing:
echo test("string"); returns true as it should, but using echo test("hello"); should return false, but returns nothing, why?
What should be used instead for returning true/false with criteria?
Well it does work on my side
Using :
function test($var){
if($var == "string"){
return true;
}else{
return false;
}
}
echo "string:";
var_dump(test("string"));
echo "hello:";
var_dump(test("hello"));
cause the output
string:bool(true)
hello:bool(false)
When you want see the output of something always use var_dump() as false produces no output when echoed directly.
var_dump(test("hello"));
Echoing false deceptively produces no output. Try var_dump instead; it will show you the true value.
bool(false)
I see no reason why your code doesn't work, but this would be shorter:
function test($var) {
return ($var == "string");
}
Your code is dangerous - this means probably wrong.
Use === instead of ==
if ($var === "string") { ...
Read the doc ;)
I am looking for the correct way to handle a return statement with a bool/string. For example I do all my checking inside the function and return true if it all passes. However if something went wrong I would like to return a string of what went wrong rather than just return false; with a general string. Does php assume false if a var is set to anything besides true? What is the correct way to handle this? Here's an example of what I'm doing
<?php
$a = 2;
$result = CheckVar($a);
if ($result)
{
echo 'Correct!';
}
else
{
echo $result;
}
function CheckVar($var)
{
if ($var == 1)
{
return true;
}
else
{
return 'This is not the correct answer. You supplied '.$var;
}
}
?>
It seems this method works, however is this good programming etiquette? Or is there another way I should be doing this? Thank you for your time.
Does php assume false if a var is set to anything besides true?
Not at all. PHP will return whatever the variable was set to. And actually since you have a non-empty string, that's a "truthy" value (ie: true in a boolean context). Since you used if ($result) as your check and you return a "truthy" value, the condition is always true. You need to change that check to:
if ($result === true) {
...
What is the correct way to handle this?
I think it's a good enough way to handle it. An alternative would be to pass an error string variable by reference, and have the fail part of your code fill that, eg:
function check($var, &$error) {
if ($var == 1) {
return true;
} else {
$error = 'This is not the correct answer. You supplied ' . $var;
return false;
}
}
Some native PHP functions behave like this (eg: exec().) Yet another alternative is to return an array with the errors, like Jared suggested. I personally use this option when I expect multiple errors (eg: a form validation routine):
function check_stuff($stuff) {
$errors = array();
if (!$condition1) {
$errors[] = 'Condition 1 failed';
}
if (!$condition2) {
$errors[] = 'Condition 2 failed';
}
return $errors;
}
Now you can also take advantage of the fact that empty arrays are falsy:
$errors = check_stuff($your_stuff);
if (!$errors) {
echo 'No errors!';
} else {
print_r($errors);
}
You can use === to check if the returned value is boolean true. === checks the type as well the value.
if ($result === true)
{
echo 'Correct!';
}
else
{
echo $result;
}
I came up against this recently, my function would either return an error message as a string or return true like this:
function check_something(){
if(condition){
return 'error message';
}
// if we got this far all is good!
return true;
}
I would call it and check the outcome like this:
$var = check_something();
if($var !== true){
// $var is not boolean true, so it must be a string
echo $var;
}
This checks that the outcome of the function is not just a truthy string, but is explicitly a boolean true
This could be useful to someone returning true or returning false as a string.
if (is_bool($result))
{
echo 'Result is a true bool';
}
else
{
echo $result.'returning a string';
}
Is this possible? I see some native php functions can do that. For example: strpos() can return 0 which can apparently be true.
Edit
When the manual says some function can return both integer 0 and boolean false, it means it can return either integer 0 or boolean false (not both) in any given call. PHP is not strictly typed, functions can return different types in different situations. For instance, the following function returns either 0 or false, depending on whether the passed parameter is non negative or not:
function myfunc($arg) {
if ($arg >= 0)
return 0;
else
return false;
}
Original
PHP has no multiple return. You have two options:
Return composite values instead
function myfunc() {
return array(0, true); //return array
}
class MyOutputHolder {
private $number;
private $truth;
function getNumber { return $this->number; }
function getTruth { return $this->truth; }
function __construct($number, $truth) {
$this->number = $number;
$this->truth = $truth;
}
}
function myfunc() {
return new MyOutputHolder(0, true); //return object
}
A third possibility is a custom resource, but that must be implemented internally (in an extension).
Use output parameters
function myfunc(&$outnumber, &$outtruth) {
$outnumber = 0;
$outtruth = true;
}
Of course, you can return only 0 or true and use only one parameter.
For functions that can return successfully with the return value of zero, you should be using type equivalence checking.
if(somefunction() !== false) {
}
The integer zero is interpreted as false if type is not considered. For example, assuming somefunction returns zero.
somefunction() != false
Will be false, while
somefunction() !== false
Will be true.
Your confusion is that strpos returns the zero-based index of the search string.
So in this case, 0 is a valid return, it means "found it at index 0"
If the string isn't found at all, then it returns FALSE.
It's important to note what's written in big red warning in the strpos doc page:
This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please read
the section on Booleans for more
information. Use the === operator for
testing the return value of this
function.
ie: 0 is not exactly FALSE in php. It's fundamental of php. 0 == FALSE but 0 !== FALSE
As too why PHP can return either a numeric value or a boolean - maybe that's your actual question - PHP isn't strongly typed, you never specify what you'll be returning, so you're free to return different data types depending on the outcome of the function
Does this count?
function stupid() {
return "0\0";
};
echo stupid() ."\n";
var_dump(stupid());
if (stupid()) echo "true\n";
echo stupid() + 4 . "\n";
Output:
0
string(2) "0"
true
4
*ducks*
A function can only ever have one return value. However, you can return an array with multiple values if you need to.
I think you're misunderstanding what strpos actually returns...
strpos() returns either an integer greater than or equal to zero, or it returns false (if the needle character is not found in the string).
0 does not equal true in any sense - what the PHP documentation does mention, though, is that because of PHP's loose-typing, 0 can equal false unless you use the conditional operator that forces type as well as value comparison.
var_dump(0 == false); // 'true'
var_dump(0 == true); // 'false'
var_dump(0 === false); // 'false'
var_dump(0 === true); // 'false'
var_dump(0 !== false); // 'true'
this is why the PHP manual recommends you test the return value from strpos() with '!== false' because the character you are searching for may be the first character in the string and therefore the function returns 0.
$string = "_testing";
var_dump(strpos($string, '_')); // 0
var_dump(strpos($string, '_') !== false); // 'true'
var_dump(strpos($string, '_') === true); // 'false'
return 0 && true;