w3resource

PHP Array Exercises : Sort an array using case-insensitive natural ordering

PHP Array: Exercise-24 with Solution

Write a PHP script to sort an array using case-insensitive natural ordering.

Sample Solution:

PHP Code:

<?php
$colors = array(
    "color1", "color20", "color3", "color2"
);
sort($colors, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($colors as $key => $val) {
    echo "Colors[" . $key . "] = " . $val . "\n";
}
?>

Sample Output:

Colors[0] = color1                                          
Colors[1] = color2                                          
Colors[2] = color3                                          
Colors[3] = color20

Flowchart:

Flowchart: PHP - Sort an array using case-insensitive natural ordering

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to sort a multi-dimensional array set by a specific key.
Next: Write a PHP function to sort entity letters.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

PHP: Tips of the Day

Shorthand notation for echo: When outside of PHP tags, a shorthand notation for echo is available by default, using to end it.

Example:

<?=$variable?>
<?= "This is PHP Tips" ?>

Output:

This is PHP Tips

Note that there is no terminating ;. This works because the closing PHP tag acts as the terminator for the single statement. So, it is conventional to omit the semicolon in this shorthand notation.

Priority of print

Although the print is language construction it has priority like operator. It places between = += -= *= **= /= .= %= &= and and operators and has left association.

Example:

<?php
echo '2' . print '5' + 3;
?>

Output:

821

Same example with brackets:

<?php
echo '2' . print ('5' + 3);
?>

Output:

821