php

How to sort an array in alphabetical order in PHP

In this tutorial, we are going to see how to sort an array in alphabetical order in PHP. The PHP functions sort() and rsort() can be used to sort arrays alphabetically.
 

Sort in ascending order

You can use sort() function to sort array elements or values alphabetically in ascending order.

<?php
	$languages = array("PHP", "Java", "Ada", "HTML", "CSS", "Fortran");
 
	// Sorting the array in ascending order
	sort($languages);
	print_r($languages);
?>

Output:

Array (
	[0] => Ada 
	[1] => CSS 
	[2] => Fortran 
	[3] => HTML 
	[4] => Java 
	[5] => PHP 
 )

 

 

Sort in descending order

You can use the rsort() function to sort array elements or values alphabetically in descending order.

<?php
	$languages = array("PHP", "Java", "Ada", "HTML", "CSS", "Fortran");
 
	// Sorting the array in descending order
	rsort($languages);
	print_r($languages);
?>

Output:

Array (
	[0] => PHP 
	[1] => Java 
	[2] => HTML 
	[3] => Fortran 
	[4] => CSS 
	[5] => Ada 
)
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *