-1

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

 $followers = $actionRequest->followers ? [
   'instagram' => $actionRequest->followers?->instagram,
    'tiktok' => $actionRequest->followers?->tiktok,
 ] : null;
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345

2 Answers2

-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

-1

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.

zohrehda
  • 625
  • 5
  • 10