w3resource

PHP Array Exercises : Sort an associative array by values


34. Sort Associative Array (Case-Sensitive by Values)

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:

Flowchart: PHP - Sort an associative array by values

For more Practice: Solve these Related Problems:

  • Write a PHP script to sort an associative array containing alphanumeric values in ascending order by value with case sensitivity.
  • Write a PHP function to sort the array in descending order by value while preserving the keys.
  • Write a PHP program to compare two sorting methods for an associative array (one using asort() and another using uasort()) and display the outputs.
  • Write a PHP script to sort an associative array by its values and then output the sorted array in a formatted table.

Go to:


PREV : Search Value Within Associative Array.
NEXT : Trim All Array Elements Using array_walk.

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.



Follow us on Facebook and Twitter for latest update.