Function not returning - php

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

Related

When is it useful to use a PHP function that ends with return;

What are the best usages of functions that end with "return;" and what are the advantages of writing a function that ends this way?
Example:
function MyFunction() {
// (do something)
return;
}
Thank you
You shouldn't, I would always use return null; so that it is an explicit declaration of what is returned (even if it is null). I'm sure this is also in one of the PSR specs as well, but I don't know them well. To confirm that return; === return null;:
function test() {
return;
}
var_dump(test());
// NULL
As to when you would want to return null;..any function that returns something, should always return something. So maybe if you have a function that gathers and returns a value from a DB, and an error occurs:
public function retrieveData()
{
$data = DB::retrieve();
if(!$data) {
return null;
}
return $data;
}
However, a lot of functions that may have errors just return true/false on success or failure so you won't necessarily use this often.
My main point to drive home: if you don't want/need to return anything, don't return anything.
A return; says only "thats the end". Mostly useful in following examples:
function test($string) {
if(empty($string)) {
return; // If the variable is empty, then stop to work!
}
echo $string;
}
A simple example is that you can write a PHP function that spits out formatted HTML:
function printHeader($value)
{
echo "<h1>$value</h1>";
return;
}
However, since you are not returning anything, the return statement is unnecessary and can be left out.
If you are talking about a empty return;, I can think of one example, if you have code that should be executed under a condition, and more code that should be executed if that condition is not met.
function MyFunction() {
if(a < 1) {
// (do something)
return;
}
// If a >= 0 it executes the code above and the code below
// Do something else
}

PHP return the value but false

I have this simple function:
function isMember($uID, $pdo) {
$status = getUserStatus($uID, $pdo);
if(isAllowed($status['status']))
return $status['status'];
return false;
}
Now I am looking for a way to return false yes, but to return also the value of the variable.
I tried the following, but it makes it empty anyway:
return $status['status'] == false;
So the logi is return false anyway but give me back also the value of the variable, even if it's false, because false should not mean empty :)
Return an array, and use the list() method to get your results:
function isMember($uID, $pdo) {
$status = getUserStatus($uID, $pdo);
$statusString = $status['status'];
$statusFlag = false;
if(isAllowed($status['status']))
$statusFlag = true;
return array($statusFlag,statusString);
}
//usage
list($flag,$msg) = isMember(5,"whatever");
echo "Access: $flag, with message $msg";
A function can not return multiple values, but similar results can be obtained by (1) returning an array or by (2) passing a variable by reference and storing the value you want returned in that variable.
You will need to write your function in a way that it returns an array containing the following:
The value you wan't returned
A flag that signifies true/false
Pass a variable by reference into your function and store the value of the status in that variable.
function isMember($uID, $pdo, &statByRef) {
$status = getUserStatus($uID, $pdo);
if(isAllowed($status['status'])) {
return $status['status'];
}
$statByRef = $status['status'];
return false;
}
False returns empty in PHP, see http://php.net/manual/en/function.empty.php
From documentation:
Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.
Try using something like this:
function isMember($uID, $pdo) {
$status = getUserStatus($uID, $pdo);
if(isAllowed($status['status'])){
return $status['status'];
}
return false;
} // If isAllowed returns true, then PHP will return $Status['Status'];, if not then PHP will by default return false.
I have noticed you haven't used braces which makes the code a little awkward to debug. Then validate like:
if (isMember($Var,$AnotherVar) !== false){
//isMember has not returned false, so PHP is operating within these braces
}
Such a simple thing, which should be most effective.
If your wanting to assign true/false to $status['status']; then you are performing the right method, but wrong operator.
== is a comparision operator. Not assignment
= is an assignment operator, so your assignment should be:
$status['status'] = false;

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

String value equals true

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 ==

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

Categories