PHP - While function

Asked

Viewed 191 times

-2

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

Here’s how it works: User has an X number of credits - column credits in the database. It uses 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 user created (or each line read) the user’s credit_creator 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 that when the number of credits is 0 or less than the number of lines, the system would stop and present a message. I don’t know if it’s right what I did, but I’ve been doing an Internet search.

  • What would be the doubt? Have how to post what developed?

1 answer

0


It is 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 decrease the variable $crediting while the variable $crediting is greater than or equal to the number of lines in the spreadsheet.

 $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 don’t know if I’ve researched your idea, but for the logic that wants to reach the code posted above, the loop DO WHILE 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--;            
 }

To $i starting at zero, being $i less than $linhas_tablela and every interaction of the loop FOR incrementing one more in the variable $i. The trick here is the use of break within the condition IF to escape the repeat loop case $crediting has reached zero.

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

Debug Rotina

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

  • I added this code to my system and it did not work as I would like. It creates users, but does not take into account the credits of the creator user. If the user has 4 credits, the system creates the number of lines independent of these 4 credits. Can I put the Pastebin link with the code? Here it does not fit,

  • Change your question and add the rest of the code or create another question and notify here by comment!

Browser other questions tagged

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