I am doing an exercise in which the user inserts a text in a textarea and I have to separate the text into words and then show the arrays sorted, both ascending (alphabetically) and descending (the alphabet in reverse), without distinguishing between upper case and lower case.
This would be the HTML part:
<label for="textarea">Inserte el contenido del texto</label>
<br><br>
<textarea name="textarea" rows="20" cols="50"></textarea>
<br><br>
<label for="selectordenar"> Seleccione cómo quiere ordenar </label>
<select name="selectordenar" id="selectordenar">
<option value="-1">Seleccione cómo quiere ordenar</option>
<option value="ascendente">Orden Ascendente</option>
<option value="descendente">Orden Descendente</option>
</select>
<br><br>
<input type="submit" value="Ordenar" name="ordenar">
</form>
</body>
</html>
And this the PHP part:
if(isset($_POST['ordenar'])){ //Si he seleccionado ordenar
$texto=$_POST['textarea']; //Cojo las palabras
$palabras=explode(" ",$texto); //Separo el texto en palabras mediante el método explode
if(isset($_POST['selectordenar'])){
$orden=$_POST['selectordenar'];
if($orden=="ascendente"){
natcasesort($palabras); //Con la función natcasesort ordeno las palabras de forma alfabética de forma insensible a mayúsculas y minúsculas
print_r($palabras);
} else if($orden=="descendente"){
print_r("Has seleccionado ordenar de forma descendente");
natcasesort($palabras); //Con la función natcasesort ordeno las palabras de forma alfabética de forma insensible a mayúsculas y minúsculas
array_reverse($palabras); //Invierto el array, ya que tiene que estar ordenado de forma descendente
print_r($palabras); //Lo muestro en pantalla
} else if ($orden==-1){
print_r("Tienes que seleccionar una forma de ordenar el texto");
}
}
The thing is that for the ascending form OK, but for the descending sort it does the natcasesort but it doesn't do the array_reverse. I understand, however, that there must be some way to sort descending directly without being case sensitive, but I haven't found anything. Any ideas? Thanks.
The array_reverse() function does n't directly modify the array like it does
natcasesort()
, so you 'll need to specify where you want to store the new array in reverse order:Just change:
By: