How to use if / else inside a function?

1

I'm trying to create a simple function, to write the title according to the gender selection in the form, but I must be doing something wrong:

$sexo = empty($_POST['sexo']) ? "[sexo]" : $_POST['sexo'];

function mudasexo($sexo) {

    if ($sexo == "masculino") {
            echo "O senhor";
        }
    else {
        echo "A senhora";
    }
}

So I wanted to use this function inside HTML texts with: <?php mudasexo() ?> but it is not working. It does not report any errors when debug , but the page does not even open.

    
asked by anonymous 04.08.2015 / 15:27

2 answers

4

I would do different, I see several conceptual errors in the function, but the only problem that prevents the function is calling the function in HTML, the function expects a parameter, you are not passing any argument. I think this is your argument:

<?php mudasexo(empty($_POST['sexo']) ? "[sexo]" : $_POST['sexo']) ?>

Even with the problem, if nothing is appearing then there are problems in other parts of the code.

According to the comments, the real problem was in the function declaration but it is still worth rethinking it.

    
04.08.2015 / 15:33
3

You can do this as follows:

function mudarSexo($sexo){

    switch($sexo){
        default: 
            $mudanca = 'Sexo não selecionado';
            break;

        case 'masculino':
            $mudanca = 'Senhor';
            break;

        case 'feminino':
            $mudanca = 'Senhora';
            break;      
    }

    return $mudanca;
}

echo mudarSexo("masculino"); // Imprime -> Senhor
echo mudarSexo("feminino"); // Imprime -> Senhora
echo mudarSexo(""); // Imprime -> Sexo não selecionado
    
04.08.2015 / 15:34