Create a function full of elements and that returns two values in php

Asked

Viewed 25 times

-1

How can I do a function with this code, since I will have to repeat it several times and the only things that change are the variables $a and $b. I need to use in my html the return of the two resulting variables ($title and $subtitle).

$situacao = 0;
$sql =  "SELECT * FROM `ed_painel` where (idaluno = '$id' or idaluno = '$id2') and a = '$a' and b ='$b' ;"; 
$result = $conn->query($sql); 
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$situacao =  $row["situacao"];
$obs =  $row["obs"];
} }

if ($situacao > 3 and $situacao < 7) {
    $titulo = "AGUARDE";    }
else {
    $titulo = "PENDENTE";
    $subtitulo = '$obs';
   }

I know it’s not like that, but it would be something like that:

funcaoteste (1,2) //variáveis $a e $b
<h1> $titulo </h1> <br>
<h2> $subtitulo </h2> <br>


funcaoteste (7,3) //variáveis $a e $b
<h1> $titulo </h1> <br>
<h2> $subtitulo </h2> <br>


funcaoteste (4,1) //variáveis $a e $b
<h1> $titulo </h1> <br>
<h2> $subtitulo </h2> <br>

1 answer

1


PHP cannot return multiple values directly (which is possible in Golang and Vlang, for example). You should use an "array" for this, it would be the easiest way, you can use the list() to simplify the process.

Therefore:

function funcaoteste(int $a, int $b) : array { 
    $situacao = 0;
    $sql = "SELECT * FROM `ed_painel` WHERE (idaluno = '$id' OR idaluno = '$id2') AND a = '$a' AND b ='$b' ;";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $situacao = $row["situacao"];
            $obs = $row["obs"];
        }
    }

    if ($situacao > 3 && $situacao < 7) {
        return ["AGUARDE", ""];
    }

    return ["PENDENTE", $obs];
}

So you could use how:

[$titulo, $subtitulo] = funcaoteste(1,2)
<h1> $titulo </h1> <br>
<h2> $subtitulo </h2> <br>

This should only work on the latest versions of PHP. I’m ignoring other code problems.


You can also return something like ["titulo": $t, "subtitulo": $st] and use something like $resposta_do_funcaoteste["titulo"].

  • Hey, buddy, thanks for helping out. When testing, I come across the following error: Fatal error: Uncaught Error: Call to a Member Function query() on null in .... on line 59. Have any idea what might be?

  • @Browser I just copy your own code, the line should be the $result = $conn->query($sql);, you must define the $conn, as well as the $id and $id2.

  • Perfect friend, it really was that, thank you very much.

Browser other questions tagged

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