Multiple return statements in a PHP function - php

I have the following PHP function
function newUser($username, $password) {
$checkUsernameAvailablity = check($username);
if (!$checkUsernameAvailablity)
{
return -1;
}
$checkPasswordComplexity = checkpass($password);
if (!$checkPasswordComplexity)
{
return -2
}
}
I would like to know if the username is taken and the password is not complex enough, will PHP stop the function after it returns -1 or will it continue and return -2 also.
Thanks in advance,
RayQuang

When execution reaches a return statement, the function will stop and return that value without processing any more of the function.

return statement returns the value and terminates the execution of the function. If the return is hit, no further code is executed in that body.
By the way, not all code paths have return values.

the design of your function is wrong.
I would return different values when the function ends accordingly.
For multiple returns I would use switch or a properly designed IF statements.
Or better return an associative array.

Related

Can i end While loop with function?

I tried to google this and i think it can't be done but i have to ask anyway.
If i have while loop?
while ($smth > 1)
{
func();
}
Is there a way i could exit the while loop immediately with that function inside it?
Maybe that function returns something that stop loop?
I tried
func(){
return break;}
but this doesn't work.
It's not possible the way you've done it -- you can't return a break. But you can return a value that could signal to exit the loop.
function func() {
return true
}
And then
while($smth > 1) {
if(func()) break;
}
This will run the function, but it will also check it's return value to verify it does not need to exit the loop. If the function returned true, the if statement is satisfied and so a break will occur. If the function doesn't return explicitly, the if will not be satisfied.
You sort of can get out of that while loop from inside that function by throwing an exception. Your teammates will not like you anymore, however.

Why we use return in the end of function while not returning any value

I am confused about return statement , why we need to use return in end of function , for example
function test($a){blah;
blahh ;
blahhh;
blahhhhh;
return;}
What the use of return here? Function automatically terminates when all the statements executed , I think there is no use of return here , but this picture from http://www.w3resource.com/php/statement/return.php make me confused
So
Can someone please explain the use of return (when we not returning any value).
It depends on what you're trying to achieve.
If you write echo in several places, your code will get confusing. In general, a function that returns a value is also more versatile, since the caller can decide whether to further manipulate that value or immediately print it.
I'd recommend to stick to the convention and use return for a function.
You should check GuardClause.
Example:
function test() {
return 10;
}
$a = test(); // $a stores the value 10
echo $a; // Prints 10
echo $a + 5; // We may want to manipulate the value returned by the function. So, it prints 15.
For further reference, check What is the difference between PHP echo and PHP return in plain English?
In that context: You don't.
return breaks out of the function, but since it is the last statement in that function, you would break out of it anyway without the statement.
return passes its argument back to the caller, but since it doesn't have an argument, there is nothing to pass.
So it does nothing.
Don't assume that every piece of code you stumble across has a purpuse. It might be left over from an earlier version of the code where something else (which gave it meaning) has been removed. It might be written by someone cargo culting. It might be placeholder for future development.
"return" is important when you plan to call this function from other codes, it helps you to:
Know if the function works correctly, or not.
Obtain values from a function.
Make sure other codes are not executed after return.
It might be useless when the code is simple as your sample, let's make it more complex.
function test($a){
if(file_exists($a)){
if(is_file($a)){
return $a." IS A FILE\n";
} else if(is_dir($a)) {
return $a." IS A DIR\n";
} else {
return $a." EXISTS, BUT I DONT KNOW WHAT IT IS\n"
}
} else {
return $a." NOT EXISTS\n";
}
return 0;
}
$filecheck = test("/abc/def.txt");
if($filecheck){
echo $filecheck;
} else {
echo "unknown error";
}
Above shows how to return a value, and do some basic handling.
It is always good to implement return in your functions so you can even specify error code for your functions for reference.
Based on your example, I'll modify slightly like below:
function test($a){
blah;
blahh;
blahhh;
blahhhhh;
return 1;
}
So I know the code is running to last line.
Otherwise the function just finishes silently.
It's useful if you want a function to return a value.
i.e.
Function FavouritePie($who) {
switch($who) {
case 'John':
return 'apple';
case 'Peter':
return 'Rhubarb';
}
}
So, considering the following:
$WhatPie = FavouritePie('John');
echo $WhatPie;
would give
apple
In a really simple form, it's useful if you want a function to return something, i.e. process it and pass something back. Without a return, you'd just be performing a function with a dead end.
Some further reading:
http://php.net/manual/en/function.return.php
http://php.net/manual/en/functions.returning-values.php
To add some further context specific to the answer, if the question boils down to "Do I need to add a return for the sake of it, at the end of a function, then the answer is no. But that doesn't mean the correct answer is always to leave out your return.
it depends what you want to do with $a.
If you echo $a within the function, that function will spit out $a as soon as it is called. If you return $a, assuming you set the calling of test to a variable (i.e. $something = $test('foo')), then you can use it later on.

PHP not iterating through nested JSON properly

I am trying to loop through a JSON Object (DATA) containing three nested JSON Objects (NEWUSERS,NEWUSERDATA,NEWRELATIONS), using a switch function to choose the appropriate function for a MySQL insert. Each function housed in the switch is called once as I loop through the keys, but they ALL seem to only ever receive the NEWRELATIONS object. Consequently, the functions fail with the exception of insertNewTestRelations, the function intended to receive the NEWRELATIONS object. I think the answer must be staring me in the face, but can anybody think why the JSON object is being reused?
Reading and iterating JSON
$json=json_decode($_SERVER['HTTP_JSON'],true);
$data=$json['DATA'];
foreach($data as $key=>$json_obj){
$result=null;
$result=$db->insertNewSwitch($key,$json_obj,$last_sync);
$response[$key.":errors"]=$result['errors'];
$response[$key.":successes"]=$result['successes'];
}
Switch function
public function insertNewSwitch($key,$json_obj,$last_sync){
$result;
if($key="NEWUSERS"){
$result=$this->insertNewTestUsers($json_obj,$last_sync,$key);
}
if($key="NEWUSERDATA"){
$result=$this->insertNewTestUserdata($json_obj,$last_sync,$key);
}
if($key="NEWRELATIONS"){
$result=$this->insertNewTestRelations($json_obj,$last_sync,$key);
}
return $result;
}
Try using else in your logical operator for the switch, and also double equals for comparisons
public function insertNewSwitch($key,$json_obj,$last_sync){
$result;
if($key=="NEWUSERS"){
$result=$this->insertNewTestUsers($json_obj,$last_sync,$key);
}
else if($key=="NEWUSERDATA"){
$result=$this->insertNewTestUserdata($json_obj,$last_sync,$key);
}
else if($key=="NEWRELATIONS"){
$result=$this->insertNewTestRelations($json_obj,$last_sync,$key);
}
return $result;
}
You are using = not ==. This is most likely your problem.
Because you are assigning the values, it will evaluate to true each time, so each statement will be entered.

PHP - Could this if statement EVER return true?

I'm trying to edit my co-worker's code (he's on vacation and out of reach) and there is this if statement:
if($this->carrier() == 1 and $this->carrier() == 2) {
return 'V';
}
My hope is that he accidentally put "and" instead of "or" which could explain a bug I'm getting, but he knows much more about PHP than I do and I want to be sure that this is wrong instead of just counter intuitive.
Yes, since it's a function with potential side effects, it might be true.
For example:
function carrier() {
return $someValue++;
}
Yes. The carrier() method could increment whatever value it returns each time you call it.
There's a small chance it could, yes.
He's calling a function twice, and you've not included the text of that function. So that could be doing something we can't see, like counting the number of times it's been called by this process.
On the other hand, it's much more likely that it is indeed a typo.
It is possible. Here is a working example you can run.
class program
{
private $i = 1;
function carrier()
{
$this->i=$this->i+1;
return $this->i-1;
}
function run()
{
if ($this->carrier()==1 && $this->carrier()==2)
{
echo "works";
}
else
{
echo "doesnt work" . $i;
}
}
}
$prog = new Program();
$prog->run();

php check function return

I have a function which return a loop, now I want to check if this function returns null or empty
That's the function:
function getCopy($pname){
function listCopy($block) {
foreach ($block as $b) {
echo '<div class="copy">'.$b->getBlock().'</div>'. "\n";
}
}
$filter=array(
new DFC(classContent::FIELD_PNAME, $pname, DFC::CONTAINS),
new DFC(classContent::FIELD_TYPE, 'copy', DFC::CONTAINS),
);
$block=classContent::findByFilter(conn(), $filter);
return listCopy($block);
}
That's my logic:
if( isset (getCopy($pname)) ){
echo "<label for='copy'>Copy</label><br>"
."<textarea name='copy' id='copy' rows='10' cols='60'>".getCopy($pname)
."</textarea><br>";
}
The isset doesn't work and neither if(getCopy($pname) != '') does.
Any idea on how to do this?
Thanks in advance
Mauro
use empty or is_null or a combination of both.
Or you could just negate the check by doing if( !getCopy($pname) ) ){ ... } but i'd go with any of the two functions above.
Edit: as deceze noted, you can't directly evaluate the return value with empty, you'll have to assign it to a var first and then pass that var to empty()
$result = getCopy($pname);
if(empty($result)) { ... }
You can't "return a loop" from a function. You can only return values. The listCopy function does not return anything, it just outputs. Hence getCopy doesn't return anything either. Defining a function within a function is usually bad practice as well, you won't be able to call getCopy twice in your case.
I'm not really sure what you're trying to do, but you need to rethink your approach.
The php function isset()is used to determine if a variable is set and is not NULL. So it's normal that it is not working.
empty() is what you are looking for but bare in mind these two points:
You shouldn't declare functions within functions.
Your function will never return something, it's always void since you don't return anything. So empty() will always evaluate to true.

Categories