PHP Array Exercises : Sort an associative array by values
PHP Array: Exercise-34 with Solution
Write a PHP program to sort an associative array (alphanumeric with case-sensitive data) by values.
Sample Solution:
PHP Code:
<?php
// Define an associative array with string keys and values
$test_array = array(
0 => 'example1',
1 => 'Example11',
2 => 'example10',
3 => 'Example6',
4 => 'example4',
5 => 'EXAMPLE40',
6 => 'example10'
);
// Sort the array maintaining index association, using a case-insensitive natural order sort
asort($test_array, SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL);
// Display the sorted array using print_r
print_r($test_array);
?>
Output:
Array ( [0] => example1 [4] => example4 [3] => Example6 [2] => example10 [6] => example10 [1] => Example11 [5] => EXAMPLE40 )
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP function to search a specified value within the values of an associative array.
Next: Write a PHP script to trim all the elements in an array using array_walk function.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/php-exercises/php-array-exercise-34.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics