PHP - While Function

-2

Good morning, I have a question regarding the while function in my Laravel project.

It works like this: User has an X number of credits - credits column in the database. It upa an xlsx file with the data of new users, the system counts the number of lines ( $rows ) and opens a foreach to access each line and create a user.

The idea is that each user was worth 1 credit - that is - for each created user (or each line read) the credit of the user_river reduced by 1 until it reached the value of 0 and the system stopped.

$credito = $usuarioLogado->creditos; 
$linhas_tabela = $dadosPlanilha->count(); 
do { (código de criação do novo usuário) $credito--; } while ($credito >= $linhas_tabela;

I wanted the system to stop and display a message when the number of credits was 0 or less than the number of lines. I do not know if it is right what I did, but I went searching the internet.

    
asked by anonymous 16.01.2018 / 12:18

1 answer

0

It's good to always assimilate the code with interpretive text so as not to confuse this beginning, in the case below:

do    = Faça
While = Enquanto
  

Create the new user and decrypt the $ credit   while the $ credit variable is greater than or equal to the number of lines in the   worksheet.

 $credito       = $usuarioLogado->creditos; //1
 $linhas_tabela = $dadosPlanilha->count(); //2
 do { 
      (código de criação do novo usuário) 
      $credito--; 
 }while($credito >= $linhas_tabela);

I do not know if I caught your idea, but for the logic that wants to hit the code posted above, the DO WHILE loop will not work well. It would be better to use a FOR and a break as below:

 $credito       = $usuarioLogado->creditos; 
 $linhas_tabela = $dadosPlanilha->count(); 
 for($i=0;$i<$linhas_tabela;$i++){
     if($credito == 0) break;
     (código de criação do novo usuário) 
     $credito--;            
 }

For $ i starting at zero, $ i $ rows_tablela and every loop FOR strong> by incrementing one more in the $ i variable. The bad thing here is the use of break within the IF condition to escape the loopback if $ credit has reached zero.

Update: Check your entire routine again, as debug of the image below, the code I posted works perfect!

Please edit your question and add the php code inside it to follow the rules of the stack.

    
16.01.2018 / 15:21