What does this code do? [duplicate]

1
<?php $campo == "Não Informado" ?: $campo = ''; ?>

In my theory if field is equal to Uninformed it will return field as empty otherwise it will keep the value, am I right?

    
asked by anonymous 05.10.2017 / 20:12

1 answer

5

This code is pretty confusing, but it does a simple thing: if the value of $campo is "Não Informado" , it turns the value of the field into '' .

The first thing executed in this code is $campo == "Não informado" . This gives false and the expression becomes false ?: $campo = '' . From here it is a ternary operator ?: "normal", but with the second term (that executes if the first one is true ) blank.

A much clearer way to write the same code, also in a row, would be:

 if($campo == "Não Informado") $campo = '';

In its original example, the ternary operator is being used for flow control, which is not its ideal function. This often causes confusion.

    
05.10.2017 / 20:36