Why isset does not work well with $ _POST? [duplicate]

0

I need the title of the page to vary according to the form, for this I used the code inside <head> :

<?php
    $titulo = isset($_POST['titulo']) ? $_POST['titulo'] : 'Sem titulo';
?>
<title><?php echo $titulo." - Minimalist";?></title>

It works fine if I add the title in the form, but it does not return the 'Untitled', when it is empty. This worked fine with $_GET . By chance, when using $_POST , does it return an empty string ?

    
asked by anonymous 18.09.2016 / 00:49

1 answer

1

The isset checks if a variable has been defined / initialized, is not checked if it has a value.

isset will always return true to $_POST because it goes always be defined, but it may be empty, which is probably the source of your problem.

See the $_POST documentation:

  

This is a superglobal , or global automatic, variable. This   simply means that it is available in all scopes by the    script .

To check if the variable is empty, use empty :

$titulo = empty($_POST['titulo']) ? 'Sem titulo' : $_POST['titulo'];

Similar to isset , empty also checks if the variable has been initialized, but does not issue a warning . What is considered empty by empty :

  • "" (an empty string )
  • 0 ( 0 as an integer)
  • 0.0 ( 0 as a floating point)
  • "0" ( 0 as a string )
  • NULL
  • FALSE
  • array() (a% empty%)
  • array (a declared variable, but no value)

According to the documentation , $var; is essentially equivalent to empty .

Another alternative is to use !isset($var) || $var == false and a condition to check if variable is not empty:

$titulo = isset($_POST['titulo']) && $_POST['titulo'] !== '' ? 
                                     $_POST['titulo'] : 'Sem titulo';

See also:

18.09.2016 / 00:57