skip to Main Content

What does the "?" mean in code laravel like this?

 $followers = $actionRequest->followers ? [
   'instagram' => $actionRequest->followers?->instagram,
    'tiktok' => $actionRequest->followers?->tiktok,
 ] : null;

2

Answers


  1. This is the ternary operator. It is a conditional operator just like "if".

    Given that the first operand evaluates true, evaluate as second operand, else evaluate as third operand.

    This means the code will load the followers into the variable $followers if $actionRequest->followers which might be a boolean is true but will be assigned null

    Note:
    ?-> is null safe operator. Which is a different operator altogether

    Login or Signup to reply.
  2. this is called ternary operation.

    $x = condition ? expr2 : expr3 ;
    

    the value of $x is expr2 if condition is true
    and expr3 if condition is false .

    so in your example the value of $followers if $actionRequest->followers is true, is

    [ 'instagram' => $actionRequest->followers?->instagram, 'tiktok' => $actionRequest->followers?->tiktok, ]

    , unless it return null.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search