PHP Array Exercises : Sort entity letters
25. Sort Entity Letters
Write a PHP function to sort entity letters.
Sample Solution:
PHP Code:
<?php
// Define a function to sort an array of entities
function entity_sort($my_array) {
// Iterate through each element in the array
foreach ($my_array as &$element) {
// Check if the element is not empty
if (!empty($element)) {
// Prepend the element with its first character
$element = $element[0] . $element;
}
}
// Sort the modified array
sort($my_array);
// Iterate through each element in the array
foreach ($my_array as &$element) {
// Remove the first character from each element
$element = substr($element, 1);
}
// Return the sorted array
return $my_array;
}
// Create an array containing space, "&", and ">"
$arr = array(" ", "<", "&");
// Call the entity_sort function and print the result
print_r(entity_sort($arr));
?>
Output:
Array ( [0] => [1] => & [2] => < )
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP function to sort the letters in a given string alphabetically and return the sorted string.
- Write a PHP script to convert a string to an array of characters, sort it, and then rejoin them into a new string.
- Write a PHP program to compare two strings by their sorted letter order and output which string is "alphabetically" smaller.
- Write a PHP script to sort each word in a sentence individually, preserving word order, and display the result.
Go to:
PREV : Case-Insensitive Natural Order Sorting.
NEXT : Shuffle Associative Array Preserving Keys.
PHP Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.