-2

Could someone explain me the following line which is in the Symfony Cookbook (FYI the main topic is dynamic generation for Submitted Forms)

I don't undersand the following: ? , neither the array() :

$sport = $event->getData()->getSport(); // getdata submited by the user in the Sport input
$positions = null === $sport ? array() : $sport->getAvailablePositions();

// is it similaire to that line? what the difference?
$positions = $event->getData()->getSport()->getAvailablePositions();
Rooneyl
  • 7,802
  • 6
  • 52
  • 81
Alexis_D
  • 1,908
  • 3
  • 16
  • 35

4 Answers4

1

? is a ternary if; which is an if statement on a single line.
It could be rewritten as

if (null === $sport) {
    $positions = array(); // an empty array
} else {
    $positions = $sport->getAvailablePositions();
}
Rooneyl
  • 7,802
  • 6
  • 52
  • 81
0

The line says, if $sport is null (=== means check both type/value), $sport will be an empty array(), if not, $sport will be $sport->getAvailablePositions();

$positions just get the result of it!

0

It's a ternary condition operator. It's the factorisation of an if then followed by an affectation.Documentation

Answers_Seeker
  • 468
  • 4
  • 11
0

This is called "Ternary Logic". You can check for a good article on this here: http://davidwalsh.name/php-shorthand-if-else-ternary-operators

The logic is:

  1. Is $sport null?
  2. If so, return an array
  3. Otherwise, get the availablePosition collection

The goal is to have something iterable at the end and in all cases, like an array, a collection, etc.

It is not similar to $positions = $event->getData()->getSport()->getAvailablePositions(); because this will throw an error if getSport() returns null, thus calling getAvailablePosition() on something null.

Ninir
  • 441
  • 4
  • 9