PHP Shorthand If/Else when using return
Asked Answered
T

6

14

There are few nice ways to write shorthands in PHP.

Less common but shortest example:

!isset( $search_order ) && $search_order = 'ASC';

More common but a little longer:

!isset( $search_order ) ? $search_order = 'ASC' : $search_order = NULL;

We can even combine examples above in to an amazing shorthand:

!isset( $_POST['unique_id'] ) && preg_match( '/^[a-zA-Z0-9]{8}$/', $_POST['unique_id'] ) ? $post_unique_id = $_POST['unique_id'] : $post_unique_id = NULL;


But how do we use examples above with functions and return, example:

function filter_gender_request($data) {  
    preg_match('/(fe)?male/i', $data, $data);
    isset($data[0]) && return $data[0]; // It doesn't work here with return
}

At the same time, if I state the following, instead of isset($data[0]) && return $data[0]; then everything works as expected:

if (isset($data[0]) ) {
    return $data[0];
}

What am I doing wrong here? If the very first and shortest example works outside of function flawlessly, why then it doesn't work with return?

Is there a possibility to use shorthands with return?

Tressa answered 27/8, 2013 at 20:12 Comment(4)
Terse code as you've shown is less readable, and therefore worse code. Save future you the headache of having to decipher what you originally meant to write by writing out the if statement.Buckskin
personally, I use: $search_order = (!isset( $search_order ) ? 'ASC' : NULL);Ronaronal
I am not sure what is being saved by writing it this way - 10 keystrokes? Here is a good piece of advice to code by.Minni
What is the problem with reading !isset( $search_order ) && $search_order = 'ASC'; What is the point of shorthands then?Tressa
S
36

With your current syntax, what do you expect your function to return when $data[0] is not set? Surely you don't expect your function to not return anything, depending upon a condition.

The only alternative I see is the ternary operator, where you return something other than $data[0] when it is not set:

return isset($data[0]) ? $data[0] : null; 
Slumberous answered 27/8, 2013 at 20:14 Comment(3)
Thanks, Nick! I thought, I tried this; your example works! I don't care if it's set to NULL at this point or not, as it will be processed later and if it's not set it will be set to NULL anyway.Tressa
@IliaRostovtsev, This is probably your best bet, and the most direct method to achieve your result. Don't forget to select your correct answer so your question doesn't linger around in Unanswered Limbo.Greerson
Jason, it will not! I never really forget! Thank you all, guys!! :)Tressa
R
28

For future googlers.

Use php 7 null coalesce (??) operator

return $data[0] ?? null; 
Religious answered 19/5, 2017 at 8:52 Comment(1)
Thanks for sharing.Tressa
M
12

Your amazing shortcut is actually rather hideous code. You are abusing the ternary operator, and that code is actually far LESS readable AND less maintainable than if you'd written it out. People expect ternaries to perform a test and return an either/or value. Performing assignment within it is NOT normal behavior.

Marsala answered 27/8, 2013 at 20:16 Comment(4)
That's a great point you make. The code is very clever indeed but maintaining it will be a painPasty
Thanks, Marc, I agree! What is the point of having shortcuts at the first place anyway, if any usage of it is an abuse?Tressa
The new $foo = isset($foo) ?: 'default value' for setting default values is a VERY handy shortcut. But that's not abusing the syntax, since it's a built-in language feature for PHP 5.4. As for the other shortcuts, !isset(...) && $foo = 'bar' looks WRONG to me, because there's a somewhat implied if() condition around all that. And seeing an assignment operation inside an if() sets off alarm bells in my head. I automatically look at it as "that should have been $foo == 'bar'" instead.Marsala
There is an open Meta discussion about this answer here: Review audit seems wrongAmaryllidaceous
F
4

The problem with your code is you are trying to execute a return statement as part of the ternary expression. The ternary operator generally results in an assignment as in:

$message = is_error() ? get_error() : 'No Errors';

This results in an assignment to $message based on the return value of is_error(). Your code is trying to process a program control statement within the operation. return cannot be assigned to the variable.

For this reason, what the other users have posted are better options for your situation.

Fritzfritze answered 27/8, 2013 at 20:31 Comment(0)
Q
2

oke I don't know what you are doing but this should work:

return ( isset($data[0]) ? $data[0] : false);
Quarta answered 27/8, 2013 at 20:19 Comment(0)
A
1

Agreeing with what has been answered here, that shorthand is harder to read once you've gone away from it and come back, or worse, another developer in the future.

Imagine yourself with even a small 500 line script file, with 40 lines of shorthand elseif as you use it, would you be ok trying to add or change code?

Especially when the subject or content is not something you're familiar with, it becomes a headache to debug or make additions.

This is much more manageable and doesn't matter what it's about, it's just code:

if ($var == 'unicorns')
  {
    $this->remove_horn;
  }
elseif ($var == 'horse')
 {
   $this->glue_on_horn;
 }
else
  {
    $this->must_be_a_zebra;
  }

just saying

Attah answered 27/8, 2013 at 20:26 Comment(3)
Do you think that there are times in code and development where one shouldn't consider maintainability? Even a quick script, small page that does one thing, should be neat, well formed and coded best practice, to adhere to current and future standards, and be maintainable...Attah
In which case your example should have used a switch statement.Tachograph
I gather that is your personal preference then, which is all it comes down to. Also, the OP used ifelse... ;)Attah

© 2022 - 2024 — McMap. All rights reserved.