2
I have this foreach
which is working perfectly, but I think it’s a very polluted, very large code. Is there any way to rewrite this foreach
in a more correct way? Everything works perfectly, but I am optimizing the code in a general way.
<?php
$dados = array(
'<tr><td>ID: 120</td></tr>',
'<tr><td>Classe de aferimento: Natural</td></tr>',
'<tr><td>Área de atuação: Airsoft</td></tr>',
'<tr><td>Valor de custo: R$ 1.220,50</td></tr>',
'<tr><td>Local: Santa-Fé</td></tr>'
);
foreach ($dados as $value) {
$valor = strip_tags(trim($value));
$xpl = explode(":",$valor);
$pos = strpos($xpl[0], "ID");
if ($pos === false) {
} else {
$cltId = trim($xpl[1]);
}
$pos = strpos($xpl[0], "Classe");
if ($pos === false) {
} else {
$cltClasse = trim($xpl[1]);
}
$pos = strpos($xpl[0], "Área");
if ($pos === false) {
} else {
$cltArea = trim($xpl[1]);
}
$pos = strpos($xpl[0], "Valor");
if ($pos === false) {
} else {
$cltValor = trim($xpl[1]);
$cltValor = explode(" ", $cltValor);
$cltValor = number_format($cltValor[1], 2, '.', '');
}
$pos = strpos($xpl[0], "Local");
if ($pos === false) {
} else {
$cltLocal = trim($xpl[1]);
}
}
echo "Dados a serem iseridos no Banco de Dados";
echo "<br />";
echo "ID do solicitante: ".$cltId;
echo "<br />";
echo "Classe do solicitante: ".$cltClasse;
echo "<br />";
echo "Área do solicitante: ".$cltArea;
echo "<br />";
echo "Valor cobrado: ".$cltValor;
echo "<br />";
echo "Local de ação: ".$cltLocal;
?>
What does the code do? What is the input and what is the output produced?
– Woss
The input is that of the $data array and the output is individual each with a different variable that are the variables starting with $clt...
– Fernando Issler
A variable
$i
is useless. Because you are using it?– Maury Developer
Really @Maurydeveloper will edit to delete.
– Fernando Issler
Where does that come from array? It will always be in that same format?
– Woss
It will always be in the same format @Andersoncarloswoss . I made a Crawler from a site where this table already exists. I separated only the <tr>.
– Fernando Issler
$pos = strpos($xpl[0], "ID");
 if ($pos === false) {
 } else {
 $cltId = trim($xpl[1]);
 }
A suggestion to minimize this code:$pos = strpos($xpl[0], "ID");
 if ($pos !== false) {
 $cltId = trim($xpl[1]);
 }
It’s useless to use comparison if you don’t perform anything.– Maury Developer
@Maurydeveloper Good! Already gave a diminished!!!
– Fernando Issler