Sort array by repeated words in PHP


I have an array in PHP (laravel) with words extracted from certain tweets. I need to be able to create a list or table where a word is displayed and the number of times it repeats in that array. That is, if the word is "hello" and it is repeated 6 times, the word appears and the number of times it repeats. Only that.

asked by Joaquin Perea 16.12.2018 в 22:53

2 answers


I do not know if it's the most efficient way to do it but I would do it with a function like this:

function palabras($str) {
$palabras = explode(" ", $str);
$palabrasArray = [];
$contador = [];
foreach($palabras as $palabra) {
  if(in_array($palabra, $palabrasArray)) {
    array_push($palabrasArray, $palabra);
  } else {
    array_push($palabrasArray, $palabra);
    $contador[$palabra] = 1;
return $contador;
  $string = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";


I forgot that it's laravel, simply believe the same but in one method

public function contarPalabras($str) {

And you call it that:

answered by 17.12.2018 в 00:32

PHP has many functions to handle arrays that greatly facilitate any work, I leave you an alternative:

//palabras a contar

//frase a usar para contar palabras
$frase='hola gato, hola perro, hola sol, adios nube, adios';

//eliminamos cualquier caracter que no sea una letra
$frase=preg_replace("/[^A-Za-z ]/", '', $frase);

//array_count_values hace el trabajo facil resumiendo el total
//de apariciones por cada elemento de un array .   
$w=array_count_values(explode(' ',$frase));


Posting result

array ( 'hola' => 3, 'gato' => 1, 'perro' => 1, 'sol' => 1, 'adios' => 2, 'nube' => 1 )

Filter words that interest me to search

//y finalmente nos quedamos con la interseccion de ambos arrays    
$matches = array_intersect_key($w, array_flip($words));



array ( 'hola' => 3, 'adios' => 2 )

Function and usage example

function contarPalabra($frase,$filtro){
    $w=array_count_values(explode(' ',preg_replace("/[^A-Za-z ]/", '', $frase)));
    return array_intersect_key($w, array_flip($filtro));

$frase='hola gato, hola perro, hola sol, adios nube, adios';

$cuenta = contarPalabra( $frase, ['gato']);



$frase='hola gato, hola perro, hola sol, adios nube, adios';

echo '<hr>';
$cuenta = contarPalabra( $frase, ['hola']);

echo '<hr>';
$cuenta = contarPalabra( $frase, ['perro']);

echo '<hr>';
$cuenta = contarPalabra( $frase, ['adios']);


array ( 'hola' => 3, )
array ( 'perro' => 1, )
array ( 'adios' => 2, )

On the site you can find all the functions and definitions for managing arrays. link

answered by 17.12.2018 в 05:44