Transform string into array excluding repeated values

0

In PHP I made a script that takes every word of a tring and transforms them into an array, giving explode in the empty spaces. Then it deletes the repeated words and shows each of them, like this:

<?php
$hashtag = "#caio #azul #caio #azul #leão #orelha #caio  #caio  #caio";
//
$hashtagArray = explode(" ", $hashtag);
// exclui elementos vazios
$hashtagArray = array_filter($hashtagArray);
// exclui elementos iguais
$hashtagArray = array_unique($hashtagArray);
// reseta as chaves
$hashtagArray = array_values($hashtagArray);
// cria uma array
$hashtagArrayDuplica = array();
foreach ($hashtagArray as &$value) {
    // repito a checagem, para evitar erros
    if (!in_array($value, $hashtagArrayDuplica)) {
        $hashtagArrayDuplica[] = $value;
        echo $value."<br>";
    }
}
?>

The result is this:

#caio
#azul
#leão
#orelha

What appears to be right. But incredibly on the client server, this application keeps showing repeated items, practically disregards my code, I do not know if it's the PHP version, or any other reason (I can not see the script running there, I only get print screen) .. . What can it be? Can there be any special characters? Is there another way to do this check to see if its server works?

PS: Notice that in my code I try to check 2 times if it has something repeated, it was an attempt not to give the client error, but without success.

    
asked by anonymous 06.08.2018 / 21:10

1 answer

0

Could you test that way here?

$hashtag = "#caio #azul #caio #azul #leão #orelha #caio  #caio  #caio";
//
$hashtagArray = explode(" ", $hashtag);

echo "<pre>";
print_r($hashtagArray);
echo "</pre>";

foreach ($hashtagArray as $key => $value){
  if (strlen($value)>0){
    $new[trim($value)] = $value;
  }
}

echo "<pre>";
print_r($new);
echo "</pre>";

exit();

Another question ... has this code ever made a mistake before? It might be that they are not putting your file in the right place on the server, then you would never know what is wrong, because you would be running 1 old code ...

    
07.08.2018 / 15:24