The reason for the mistake is because $tipoSemEspaco
is a new array, which is independent of the $tipos
.
An easy fix:
Add the index in the foreach
:
foreach($tipos as $index => $tipo){
/...
}
Then use it to get the respective $tipoSemEspaco
:
<?=$tipoSemEspaco[$index]?>
In the end:
<select name="tipoPessoa" class="form-control">
<?php
$tipos = array("Pessoa Fisica","Pessoa Juridica");
$tipoSemEspaco = str_replace(" ","",$tipos);
foreach ($tipos as $index => $tipo):
$esseEhOTipo = get_class($pessoa) == $tipoSemEspaco;
$selecaoTipo = $esseEhOTipo ? "selected='selected'" : "";
?>
// Linha 22 <option value="<?=$tipoSemEspaco[$index]?>" <?=$selecaoTipo?>>
<?=$tipo?>
</option>
<?php endforeach ?>
</select>
Another option would be to add something like:
$tiposPessoasDisponiveis = [
0 => ['TextoHumano' => 'Pessoa Fisica', 'ValorMaquina' => 'PessoaFisica'],
1 => ['TextoHumano' => 'Pessoa Juridica', 'ValorMaquina' => 'PessoaJuridica'],
];
Since there are few options and it does not tend to change this often, IN THIS CASE, this could be feasible, then:
<select name="tipoPessoa" class="form-control">
<?php
$tipos = [
0 => ['TextoHumano' => 'Pessoa Fisica', 'ValorMaquina' => 'PessoaFisica'],
1 => ['TextoHumano' => 'Pessoa Juridica', 'ValorMaquina' => 'PessoaJuridica'],
];
foreach ($tipos as $tipo):
$esseEhOTipo = get_class($pessoa) == $tipo['ValorMaquina'];
$selecaoTipo = $esseEhOTipo ? "selected='selected'" : "";
?>
<option value="<?=$tipo['ValorMaquina']?>" <?=$selecaoTipo?>>
<?=$tipo['TextoHumano']?>
</option>
<?php endforeach ?>
</select>
Personally I don’t think it’s very good, because it simply makes it confusing to understand what each thing is, are two different arrays and that has a direct relationship, that is my opinion, precisely for this I would prefer to do:
<select name="tipoPessoa" class="form-control">
<?php
$tiposPessoasDisponiveis = ['Pessoa Fisica', 'Pessoa Juridica'];
foreach ($tiposPessoasDisponiveis as $tipoPessoa){
$tipoSemEspacamento = str_replace(' ', '', $tipoPessoa);
$estaSelecionado = get_class($pessoa) == $tipoSemEspacamento;
$atributoOptionHTML = '';
$atributoOptionHTML .= 'value = "'.$tipoSemEspacamento.'"';
$atributoOptionHTML .= $estaSelecionado ? 'selected' : '';
?>
<option <?= $atributoOptionHTML ?>>
<?= $tipoPessoa ?>
</option>
<?php } ?>
</select>
Finally, add the str_replace
within the foreach
, in this way it becomes clear what is the purpose of it, I renamed the functions so that try to present better their "functions", in my view. But logically this is totally optional.
Implode has a totally different idea than
str_replace
in this case, maybe the OP really wants this, but I don’t think so. Thestr_replace
apparently made to remove spaces, ie thePessoa Fisica
go toPessoaFisica
. Use theimplode
will stayPessoa Fisica Pessoa Juridica
, in the same string, it does not even live up to the name "semEspaco". This does not seem to be the case at all, but it may be that this is what the PB wants anyway.– Inkeliz