if / else simplification to ternary operator - php

Can this be done for the code below. Problem I see is that there are two statements in the else clause and I couldn't figure out a way to fit in the echo...I need to return a 1 or a 0. Perhaps someone knows a trick?
function empty_user($c)
{
if((int)!in_array('',$this->a,TRUE))
{
return 1;
}
else
{
echo $c;
return 0;
}
}

No ternary =/. Although you can simplify this a lot because once the function returns, it stops interpreting the function anyway, so you can eliminate the else.
function empty_user($c) {
if ((int)!in_array('',$this->a,TRUE)) return 1;
echo $c;
return 0;
}

you generally shouldn't use ternary operators to determine execution order, but also, no, you won't be able to convert the if/else you've got there.

You can't use a ternary operator if you want more than one operation in either block, but the question is why would you want to? It is much clearer and easier to update if you have full blocks that you can continue to add code to.

in_array returns a bool which is perfect for an if statement - there is no need to cast it to an int.
function empty_user($c)
{
if (in_array('',$this->a,TRUE))
{
echo $c;
return 0;
}
return 1;
}

Related

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.

Why do you need to include the "return" keyword in a recursive function?

I have the following function that implements division without the use of a modulus operator
function division($dividend, $divisor, $quotient){
if($dividend<=$divisor){
return $quotient;
}else{
$dividend-=$divisor;
$quotient++;
division($dividend, $divisor, $quotient);
}
}
echo division(3, 2, 0);
I'm confused why I need to prepend the return keyword to the line division($dividend, $divisor, $quotient) if the function is going to iterate until the if statement evaluates to true and return $quotient evaluates.
Can someone explain why the return keyword is needed?
This is because once the quotient has been calculated, you might want to do something with it. In your case you are displaying it with the echo statement. Without the return call, you cannot know what the result of the function is.

PHP: Correct use of return in function - use variable or use a number directly?

I am looking to return an integer with a value of 50 or value of 25. Is this the correct way to do this or should I create a variable $temp1=50 and $temp2=25 and return the variable instead of just returning 50 and 25.
function somefunction($length)
{
if ($length > 50)
{
return 50;
} else {
return 25;
}
}
Sorry if duplicate, I looked.
It is perfectly fine the way you're doing it. Assigning a value to a variable to only return it makes no sense really.
As a better version to your alternative, for some more complicated cases, where you'd eventually need to return a variable, you could use only one variable instead of two as you suggested. Something more like
function somefunction($length)
{
$myVar = 0;
if ($length > 50) {
$myVar = 50;
}
else {
$myVar = 25;
}
return $myVar;
}
It is not necessary to assign a variable before. Just write
return ($length > 50 ? 50 : 25);
Assigning to a variable before returning is pointless. You're returning a value. 50 is a perfectly good value by itself, it does not need to be assigned to a variable before being returned.
In other words: you're doing it right already.
It depends on what you want to do :
if you just want to return a constant or if you want to parameter this constant.
in a case of a constant, for readability, you can name them :
define('RETURN_CONSTANT_SUP',50);
define('RETURN_CONSTANT_INF',25);
function somefunction($length)
{
if ($length > RETURN_CONSTANT_SUP)
{
return RETURN_CONSTANT_SUP;
} else {
return RETURN_CONSTANT_INF;
}
}
So you do it the right way, you can just use constant if, one day, you want to reuse those values.
I'd say the problem with your function is less the return but the input.
Anyway, your question is a bit theoretic. Because both returning a constant integer value as well as a variable would work. It wouldn't even make much of a difference. See the following example:
function somefunction($length)
{
return 25 + 25 * ($length > 50);
}
The problem with the code is that you have written it only for these specific values. So not using a variable can be a sign that the code is limited. But less because of the return and more because of the flow.
function integer_top_cut_drop($value, $top, $default)
{
$value = (int) $value;
$top = (int) $top;
$default = (int) $default;
if ($value > $top)
{
return $top;
}
return $default;
}
As this function shows, there are no numbers in there, but only variables. It pretty much does what your existing function does, but everything is variable. The numbers with their constant values have been removed and are now being passed as parameters:
function somefunction($length)
{
return integer_top_cut_drop($length, 50, 25);
}
So you normally never are concerned whether your return a variable, a constant, some other kind of expression or another functions return value.
More important is, that your code does what it has to do and you do it in a useful way.
That could mean in your code that your function already is totally fine.
But consider you enable yourself that you can re-use common parts, e.g. like shown here with a new function. That might be a bit over the top for your example, but just to show the picture.
A function can preserve the logic, so you don't need to write that part more than once. It also reduces the size of the other parts of the code using that function.
There is no correct way to do this.
This question is about style and preferences and you won't be able to get a definitive answer.
Just use what you like best (unless you are working in a team of course, in which case you should adapt the team's coding styleguide).

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

refactoring this block

I'm refactoring some code that wasn't written by me. This block sets the value of $val but I want to clean it up a bit. Obviously I can't use the tertiary operator here. What other ways I can make this code cleaner?
if (isset($vars[$input])) {
$val = $vars[$input];
} elseif (isset($this->getI['io'])) {
$val = $this->getI['io'];
} elseif (isset($vars[5])) {
$val = $vars[5];
} else {
$val = 10;
}
$val = 10;
if (isset($vars[$input])) {
$val = $vars[$input];
} elseif (isset($this->getI['io'])) {
$val = $this->getI['io'];
} elseif (isset($vars[5])) {
$val = $vars[5];
}
This is about as simple as it gets without obfuscating the code. I'd rather try to simplify the logic, it's kinda hard to comprehend why the value is being looked for in so many different places.
I'm afraid I don't know php. I'm assuming that if you were to pass (say) $vars[$input] to a function, by the time it was a parameter to the function, the parameter's set-ness would be true (if that's not the case, I'd try writing a function that tested isset() on its parameter and set $val if so). I find elseif's to add complexity; I try to avoid them. In this case, I would write a function that returned the value; then all my elseif's can become plain if's.
f() {
if (isset($vars[$input])) {
return $vars[$input];
}
if (isset($this->getI['io'])) {
return $this->getI['io'];
}
if (isset($vars[5])) {
return $vars[5];
}
return 10;
}
And, of course, in your calling function, assign $val to the result of this function.
In my opinion, your example is as clean as it gets. Sure, you could write it as a huge one-liner using the ternary operator:
$val = isset($vars[$input]) ? $vars[$input] : isset($this->getI['io'] ? $this->getI['io'] : isset($vars[5]) ? $vars[5] : 10;
But this is obviously much harder to read and to maintain, so the original example is definitely cleaner (although it might be missing some comments).
I don't know...it seems to be pretty concise, as is.
If you know what it does, it does it well and it is clean enough that you can figure it out again in the future, I say don't touch it.
While you're at it figure out what it's doing and add some comments.
e.g. why assign it to the magic number 10? maybe the context of the rest of it may shed some light.
As far as code goes, you're not going to get it any simpler than this.

Categories