0
Imagine I have the code below:
<?php
$linha1 = 0;
$linha2 = 0;
$linha3 = 0;
$linha4 = 0;
$linha5 = 0;
// Array com 5 numeros
$cincoNumeros = [1, 2, 3, 4, 5];
for($i=0;$i<50;$i++) {
// Misturo aleatoriamente o array acima
shuffle($cincoNumeros);
// Seleciono um array unitário (um número) no array que foi misturado.
$umNumero = array_slice($cincoNumeros, 0, 1);
// Pego o valor do index do array $umNumero
$valor = $umNumero[0];
// Agora, de acordo com esse número sorteado, incremendo a variavel correspondente:
switch ($valor) {
case 1:
$linha1 += 1;
break;
case 2:
$linha2 += 1;
break;
case 3:
$linha3 += 1;
break;
case 4:
$linha4 += 1;
break;
case 5:
$linha5 += 1;
break;
}
}
?>
This way it works, but imagine how big it would be if we were talking about 100, 500, 1000 line variables.
Is there any way to dynamically rename the variable, using only a FOR without SWITCH, as I suggest below?
<?php
// crio um laço com 50 loops, por exemplo
for($i=1;$i<=50;$i++) {
// Misturo aleatoriamente o array $umNumero
shuffle($cincoNumeros);
// Seleciono um array unitário (um número) no array que foi misturado.
$umNumero = array_slice($cincoNumeros, 0, 1);
// Pego o valor do index do array $umNumero
$valor = $umNumero[0];
$linha.$valor += 1; // Incremento de uma variavel linhaX qualquer, de acordo com valor sorteado. Digamos que o valor sorteado seja 3 então, a variável a ser incrementada seria $linha3.
}
?>
I know the name of the variable $line. $value is wrong. It would just be concatenating, but gives error because there is no variable "line".
I ask: Is there any way that the variable name can vary according to the selected value?
The code would be leaner than with the use of switch.
maybe swap the row variable for an array and each array position would be a row
– Igor Henrique
It can be @igorhenrique I will test. But anyway would not end up having to use a huge switch? Streamlined codes (clean) improve the performance of the web application, the page loads faster, facilitates understanding and maintenance of the code right? Whenever possible I try to optimize.
– Ronda
No. Since each position of the array represents a line, it is not necessary to check for the switch to add up, you end up doing the sum but generic.
– Igor Henrique