Logical doubt of PHP code

Asked

Viewed 185 times

1

Hello, folks. I’m starting in PHP and am having some problems with this code:

<?php

    function linha($semana) {

        echo "<tr>";
                for ($i= 0; $i <= 6; $i++) { 
                        if (isset($semana[$i])) {
                            echo "<td>{$semana[$i]}</td>";
                        } else {

                            echo "<td></td>";
                        }
                    }   

        echo "</tr>";
    }

    function calendario() {

        $dia = 1;
        $semana = array();
        while ($dia <= 31) {
            array_push($semana, $dia);

            if (count($semana) == 7) {
                linha($semana);
                $semana = array();
            }

        $dia++; 
    }

    linha($semana);

    }

?>
<table border="1">
    <tr>
        <th>Domingo</th>
        <th>Segunda</th>
        <th>Terça</th>
        <th>Quarta</th>
        <th>Quinta</th>
        <th>Sexta</th>
        <th>Sábado</th> 
    </tr>
    <?php calendario();?>
</table>

As you can see, it results in a calendar (without specifics). I cannot understand the logic of this code. Why use for? Why use the if?

If anyone can help me with the logic of this code I thank you!

1 answer

2


This calendar itself is useless. It just increments a counter without obeying any variable that a calendar has. But let’s see:

<?php 

function calendario() {

    // Define o primeiro dia como 1
    $dia = 1;

    // Define que $semana será uma variável do tipo array
    $semana = array();

    // Inicia um loop até o que seria o dia 31, desobedecendo quaisquer eventuais regras do calendário. Nem todos os meses possuem 31 dias
    while ($dia <= 31) {

        // Adiciona o valor do dia dentro do array $semana
        array_push($semana, $dia);

        // Verifica se a variável $semana possui 7 elementos
        if (count($semana) == 7) {

            // chama a função linha() e passa a variável $semana como parâmetro
            linha($semana);

            // Zera o array $semana
            $semana = array();
        }

        // incrementa +1 no valor de $dia
        $dia++; 
    }

    linha($semana);

}

The function below only iterates by the array that was passed as parameter and creates a new row in the table with the 7 elements (numbers, considered as calendar days)

function linha($semana) {

    echo "<tr>";
    for ($i= 0; $i <= 6; $i++) { 
        // verifica se possui o elemento na posição $i do array $semana
        // Caso possua, imprime o valor na tela
        if (isset($semana[$i])) {
            echo "<td>{$semana[$i]}</td>";
        } else {

            echo "<td></td>";
        }
    }   

    echo "</tr>";
}


?>
  • 1

    Thank you, Marcelo! I am training my logic and this problem was a little difficult to understand, but your explanation helped a lot!

Browser other questions tagged

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