Validate explodes

Asked

Viewed 124 times

0

Code:

$pessoa = "CARLOS";

$nome = explode ( " ", $pessoa, 2)[0];

$sobreNome = explode ( " ", $pessoa, 2 )[1] == null 
             ? "VAZIO" 
             : "sobreNome: " . explode ( " ", $pessoa, 2 )[1] ;

print "Nome: " . $nome . "<br />";
print "sobreNome: " . $sobreNome;

Goal:

If explodes ( " ", $person, 2 )[1] it is not possible because the person only register 1 name, surname gets the term EMPTINESS

How to do?

Obs.: The way I made it makes the following mistake.

Notice: Undefined offset: 1 in D:\Trabalhos\host\htdocs\hotplateprensas.com.br\teste.php on line 9
Nome: CARLOS
VAZIO

In time:

If I do:

$pessoa = "CARLOS ALBERTO";

Then there’s no mistake.

1 answer

3


If the full name of the person does not have a blank space, the function explode will return a array of only one element at zero; you cannot access index 1 assuming it will exist, because when it does not exist it will give the cited error.

Also, you called the function explode 3 times for the same string in 2 lines of code basically; this is a clear sign that you should refactor it.

$nomeCompleto = "Carlos";

$nomes = explode(" ", $nomeCompleto, 2);

$nome = array_shift($nomes);
$sobrenome = array_shift($nomes) ?? "Vazio";

Thus, $nomes will be the array returned by explode; the function array_shift will remove the first element by returning it to $nome. If there is no last name, the function array_shift will return NULL and through the null coalescence operator is assigned the value "Vazio" when this occurs.

But you can still simplify to:

$nome = $nomes[0];
$sobrenome = $nomes[1] ?? "Vazio";

For the null coalescence operator will intrinsically check whether index 1 exists in the array before returning it.

  • I will accept your answer but I would like some guidance. What do you think of this approach? $surname = ! isset ( explodes ( " ", $person, 2 )[1] ) ? "EMPTY" : explodes ( " ", $person, 2 )[1] ;

  • @Carlosrocha Unnecessary. Why perform the same function 2x?

Browser other questions tagged

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