The reason for the error is because $tipoSemEspaco
is a new array, which is independent of $tipos
.
An easy fix:
Add index to foreach
:
foreach($tipos as $index => $tipo){
/...
}
Then use it to get its $tipoSemEspaco
:
<?=$tipoSemEspaco[$index]?>
At 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 this:
$tiposPessoasDisponiveis = [
0 => ['TextoHumano' => 'Pessoa Fisica', 'ValorMaquina' => 'PessoaFisica'],
1 => ['TextoHumano' => 'Pessoa Juridica', 'ValorMaquina' => 'PessoaJuridica'],
];
Since there are few options and do 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 do not think this is very good , because it simply makes it confusing to understand what each thing is, it's two distinct arrays and it has a direct relationship, that's my opinion, :
<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, adding str_replace
to foreach
, this way it's clear what its purpose is, I've renamed the functions so that you can try to better present your "functions", in my view . But of course this is totally optional.