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.
Related
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.
I have a part in my code:
while($a = getrow()){
//code
}
getrow() is a function which keeps on returning array based on some condition.
what getrow() should return so that the while loop doesn't execute the code inside but takes the next value returned by getrow() function.
While loops will run as long as the condition remains true. So as long as you return rows, the code inside will get executed. If you return false, the while loop will terminate. If you want to conditionally avoid running code within the loop, your option is to return something like 'SKIP' and then inside the while loop check if $a == 'SKIP' and then issue a continue.
while($a = getrow()){
if($a == 'SKIP')
continue;
//code
}
You can use continue control structure for skip an iteration. Please read the docs
while($a = getrow()){
if($a == 'something'){
continue; // skip iteration
}
//rest code which you want to run
}
When creating a function with a foreach (or any possibly time consuming task) and a boolean return, will PHP wait for the foreach to complete before moving on?
Is there ever a time when PHP doesn't wait? For example, in jQuery when I write a similar function with an ajax request, I have to put all code in the ajax callback function or else it will fail.
Code example:
function is_true(){
$arr = array(true,true,true,false);
foreach($arr as $curr){
sleep(200);
if(!$curr){ return false; }
}
return true;
}
PHP will wait for the foreach to complete, but only when you call the function, not when the function is defined.
Please see my code, i am almost stuck in this, Why the break inside the array_walk not breaking...
$bool=array_walk($_POST, 'check_empty');
function check_empty($item, $key)
{
$bool=(isset($item) && $item != "") ? 1: 0 ;
if(!$bool)
{
//return 0;
break;
}
return $bool;
}
It's not at all clear what you're trying to do, but break is a control structure that exits only true loops (for, foreach, while and do-while) and switch structures.
array_walk is iterative but not a loop in the true sense.
You can't 'break' (to use the terminology) from an array walk callback; it is invoked on each element of the array as a means to update or otherwise modify each element, and I can't imagine a use case where you'd want to terminate this during it.
What are you trying to do? Your break is not working, because you're returning a value right before it - so the line with break is never executed.
If you're trying to remove all empty values from the array, try array_filter($array).
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.