Enter conditional ternary in PHP [duplicated]

0

I do not know how to include a conditional in a input that is shown through PHP.

I've tried with:

echo "<input type='text' name='status' placeholder='Introduce un estatus' value='"
. if(isset($_POST['guardar'])) { 
     $ubicacion;
} else {  
     $informacion_perfil['ubicacion'];
} . "'>";

It gives me an error: syntax error, unexpected 'if' (T_IF) , but I do not know how to solve it, and evidently this way it would be showing all the conditional, when I only want to show $ubicacion or $informacion_perfil['ubicacion'] depending on if one condition or another is fulfilled.

The only solution I found is this:

if(isset($_POST['guardar'])) {
   echo "<input type='text' name='status' placeholder='Introduce un estatus' value='" .  $status . "'>";
} else {
   echo "<input type='text' name='status' placeholder='Introduce un estatus' value='" . $informacion_perfil['estado'] . "'>";
}

I would like to know if you can do the same code in just one line.

    
asked by JetLagFox 04.04.2017 в 13:35
source

3 answers

3

It's easy with the PHP ternary comparator

echo "<input type='text' name='status' placeholder='Introduce un estatus' value='" . (isset($_POST['guardar']) ? $ubicacion : $informacion_perfil['ubicacion']) . "'>";

Is its use condición ? sentencia TRUE : sentencia FALSE ;

    
answered by 04.04.2017 / 14:01
source
2

In a single line I do not leave but in this way it is also smaller than your second proposal, if it can be useful.

if(isset($_POST['guardar'])) { $aux=$ubicacion;} else {  $aux=$informacion_perfil['ubicacion'];}

$salida = "<input type='text' name='status' placeholder='Introduce un estatus' value='".$aux."'>";

echo $salida;

I have also seen that there are alternative structures in the official php documentation in case they can help you.

    
answered by 04.04.2017 в 13:54
2

As a solution proposal I would keep both possibilities in a variable, instead of including an if in the value of an input.

For example ...

if(isset($_POST['guardar'])) { 
     $value = $ubicacion;
} else {  
     $value = $informacion_perfil['ubicacion'];
}

And then I simply call the variable in the input , such that it's like that.

echo "<input type='text' name='status' placeholder='Introduce un estatus' value='" .$value. "'>"; 
    
answered by 04.04.2017 в 13:54