phplaravel

How can I use shorthand if with return


I want to make condition with shorthand if and use return in condition how can I do something like this

Here is my controller

public function index()
{
    $all = User::all()
    $all = $this->calculatePercent($all);
    return view('dashboard.index');
}

I want to make condition

If (!empty($user)){
    $user = $user;
} else {
    return 0
}

How can I do something like this :

public function calculatePercent($user) 
{
    $query = !empty($user) ? $user : return 0;
}

Update I want to do some thing like this in my function

public function calculatePercent($user) 
{
    $user = !empty($user) ? $user : return 0;
    foreach ($user as $item) {
        $percentSell[] = ($item->total * 100)/$item->target;
    }
    return $percentSell;
}

Solution

  • Hi unfortunately you currently cannot return from one of the condition of a trinary expression (short hand if).

    Doing:

    $foo = true ? return true : false;
    

    Give you

    syntax error, unexpected 'return'
    

    That said for single line if's you can omit the {} curly brackets

    if(true) return true; else $foo = false;
    

    Which really is not that much longer. I'm not sure exactly why this is the case (cant do it in trinary). It could be because it has sort of an implied return. It could be because returning ends whatever scope you are in and the trinary cannot be completed because of that. Or it could be because it can do assignment such as this (as seen above):

    $foo = true ? return true : false;
    $foo = return true; //this gives the same syntax error
    

    Well for whatever reason, it's just not possible in the current version of PHP. Perhaps sometime in the future they may do it, but it seems like a low priority sort of thing, so I wouldn't hold my breath ... lol

    Just for completeness you can change this:

    $query = !empty($user) ? $user : return 0;
    

    Into

    if(!empty($user))$query=$user;else return 0;
    

    Also notice you can remove spaces in certain places. Shorthand stuff like this is fine, but there is something to be said about readability. For this it's probably fine, but readability is very important in code and it's much more important then being concise and short, IMO.

    When I write code my priorities are

    If it doesn't do what it's supposed to it's worthless, if you can't read it it's hard to maintain and make sure it does what it's supposed to. If it has a lot of unnecessary bloat it's hard to read and probably performs poorly. Once all those are met, then if I need to I will try to improve the performance of it.

    Anyway happy coding!