How to store a foreach variable inside an array

Asked

Viewed 81 times

-2

How can I make for that variable $aluno is not replaced within the array every time the loop in the foreach?

foreach($alunos as $index => $aluno){
    $numero_aluno = $index + 1;
    $resto = $numero_aluno % 2;

    if($resto == 0){
        $turma_B = array("$aluno",);
    }else{
        $turma_A = array("$aluno",);
    }
}
  • "the variable $student is not replaced inside the array" - if I understand correctly, you want the variable $aluno is the same throughout the foreach.. if yes, you need to understand how the foreach, pq this is the right behavior :P https://www.php.net/manual/en/control-structures.foreach.php

1 answer

0


I don’t know if I can understand exactly what you need, the question is too vague. But I believe you want to store students in two different classes.

If so, in your code you are replacing the values of $turma_A and $turma_B with each loop loop.

If I understood correctly what you need, the most appropriate code for this would be the following:

<?php 
// Criando os arrays
$turma_A = [];
$turma_B = [];

foreach($alunos as $index => $aluno){

    $numero_aluno = $index + 1;
    $resto = $numero_aluno % 2;
    
    if($resto == 0) {
        // Armazenando $aluno em uma nova posição no array $turma_B
        $turma_B[] = $aluno;
    } else {
        // Armazenando $aluno em uma nova posição no array $turma_A
        $turma_A[] = $aluno;
    }
}

Browser other questions tagged

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