Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Shorthand If/Else when using return

Tags:

php

shorthand

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?

like image 331
Ilia Avatar asked Aug 27 '13 20:08

Ilia


People also ask

Can we use if without else in PHP?

If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed. On the other hand if you need a code to execute “A” when true and “B” when false, then you can use the if / else statement.

What is short hand if?

There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line.

Can I use ternary operator in PHP?

Using the ternary operator is just like writing an “if…else” statement in PHP, but more concise and potentially more readable. This PHP operator is best used when you need to assign a variable a value based on whether a condition is true or false.


2 Answers

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; 
like image 52
nickb Avatar answered Sep 21 '22 21:09

nickb


For future googlers.

Use php 7 null coalesce (??) operator

return $data[0] ?? null; 
like image 36
Viktor Sydorenko Avatar answered Sep 20 '22 21:09

Viktor Sydorenko