What does this portion of code mean in laravel?

1

Look at this line of laravel code on the internet, however I do not know in what form it is interpreted. The line is as follows:

$oldCart = Session::has('cart') ? Session::get('cart') : null;

I would appreciate your explanation.

    
asked by lucho 13.06.2017 в 22:41
source

2 answers

1

First question : what does this code do?

$oldCart = Session::has('cart') ? Session::get('cart') : null;

the Session::has('cart') Determine if there is an element in the session in this case cart

Session::get('cart') gets the value of the session

Second Question : which means the ? and the : is not more than a short if to assign it is usually done this way:

if (Session::has('cart')){
   $oldCart =  Session::get('cart') 
}else{
   $oldCart =  null;
}

reads like this: ? then and : otherwise

  

It is obligatory to maintain this order, that is, the ? goes first and then   the :

     

It is very common to see them in other programming languages

    
answered by 13.06.2017 / 22:59
source
1

Use if online and ternary operator to assign the value of the oldCart variable. If the expression (condition) is met before "?" return the value between "?" and ":" otherwise, return the value after ":".

  • If the session has cart defined, that value is assigned to oldCart .
  • If the NO session has cart set, the value of oldCart will be null.
answered by 13.06.2017 в 23:11