What does that code do?

Asked

Viewed 66 times

1

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

In my theory if field equals Uninformed will return field as empty or keep value, I’m sure?

1 answer

5

This code is very confusing, but it does one simple thing: if the value of $campo for "Não Informado", transforms the value of the field into ''.

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

A much clearer way to write the same code, also in one line, 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.