String value equals true - php

I have a function that returns TRUE or FALSE or "Test_operation", and I am looping it to do some things. As you can see the value of $comment_reply is Test_operation.
$comment_reply = $this->Profunction->insert_comments();
echo $comment_reply; // returns Test_operation
if ($comment_reply==TRUE)
{
echo json_encode('Success');
}
elseif($comment_reply==FALSE)
{
echo json_encode('Failed');
}
elseif($comment_reply =="test_operation")
{
echo json_encode('This Action Cannot be done!');
}
But still
if ($comment_reply==TRUE)
{
echo json_encode('Success');
}
This portion getting executed. Why does it happen?
In that function I am returning like this:
return TRUE; // if all success
return FALSE; // if there is some problems
return "Test_operation"; //No insertion need to be done,may be for preview purpose.
SOLVED : I changed bool values to string.
So it will be
return 'TRUE'; // if all success
return 'FALSE'; // if there is some problems
return "Test_operation"; //No insertion need to be done,may be for preview purpose.

Not sure it's your issue, but if you want to enforce equality by type and value, use the === operator.
You can check this out in more detail on the comparison operator page.
Happy coding

Try using === instead of ==

Related

PHP if statement, does not validate, only first if runs

I have 3 stages to my if statement.
If is front page return true.
If is not front page but object is set and has certain value return true.
If not return false.
It worked as two seperate statement,
1) if is front page return true if not false
2) if object is set and has given value return true, objects is not set type return false.
When I try to put them as one statement I get true if front page but this rest doesn't return.
Code is below. Is their anything wrong with the statement? Thanks
<?php
$object = get_object();
if(is_front())
{
return 'true';
}
elseif (!(is_front() & !empty($object))) //is not front but object has been set check value
{
confirm_value();
}
else (!(is_front() & empty($object))) //if not front and object is not set
{
return 'false';
}
function confirm_value() {
$value = load($object); //load object
if($value->id($id)) //check value of id
{
return 'true';
}
else
{
return 'false';
}
}
?>
working code below
<?php
$object = get_object();
if(is_front())
{
return 'true';
}
elseif (!(is_front() && !empty($object))) //is not front but object has been set check value
{
return confirm_value();
}
else
{
return 'false';
}
function confirm_value() {
$value = load($object); //load object
if($value->id($id)) //check value of id
{
return 'true';
}
else
{
return 'false';
}
}
?>
Two problems I see:
1 - you are using a single & when you should be using &&.
2
confirm_value();
should be
return confirm_value();
I don't know the aim of code above but:
Use return confirm_value();
Else statement do not have condition. If you want check condition you should continue using elseif
Should using && instead of &. Because of & is bitwise operator. It will same result with && when all conditions are boolean. But when 1
& 2 == false

Retrieving a boolean value in a function using php

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 can't I use an "if" statement to return true/false in a PHP function?

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 ;)

PHP return false with a string

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';
}

Function not returning

function checkSessionToken($token) {
if (!isset($_SESSION['token']) || empty($_SESSION['token'])) {
return false;
}
return $token == $_SESSION['token'];
}
For some reason this function is not returning any value, while it really should, causing my script to fail. When I put the result in a variable and echo it, I don't get any output. Why is this?
Thank you
The code looks good.
Don't echo the value. Use var_dump. echo false; does not output anything (example).
var_dump will output bool(false).
return $token == $_SESSION['token']; may return NULL if there is no return value because of one of your data. You can check it with print gettype(checkSessionToken($token));.
To avoid this you could make sure to return the bool result of (foo == bar), e.g. adding parenthesis as per follow: return ($token == $_SESSION['token']);

Categories