w3resource

PHP function Exercises: Sort an array

PHP function: Exercise-4 with Solution

Write a PHP function to sort an array.

Visual Presentation:

PHP function Exercises: Sort an array

Sample Salution:

PHP Code:

<?php
// Function to sort an array in ascending order
function array_sort($a)
{
    // Iterate through each element of the array
    for ($x = 0; $x < count($a); ++$x)
    {
        // Assume the current element is the minimum
        $min = $x;

        // Iterate through the remaining elements of the array
        for ($y = $x + 1; $y < count($a); ++$y)
        {
            // If a smaller element is found, update the minimum index
            if ($a[$y] < $a[$min])
            {
                $temp = $a[$min];
                $a[$min] = $a[$y];
                $a[$y] = $temp;
            }
        }
    }

    // Return the sorted array
    return $a;
}

// Input array
$a = array(51, 14, 1, 21, 'hj');

// Call the array_sort function with the input array and print the sorted array
print_r(array_sort($a));
?>

Output:

Array                                                       
(                                                           
    [0] => hj                                               
    [1] => 1                                                
    [2] => 14                                               
    [3] => 21                                               
    [4] => 51                                               
) 

Explanation:

In the exercise above,

  • The function "array_sort()" is defined, which takes an array '$a' as input.
  • It iterates through each array element using a for loop, starting from the first element.
  • Inside the outer loop, another inner loop is used to find the minimum element among the unsorted elements.
  • The index of the minimum element is stored in the variable '$min'.
  • If a smaller element is found in the inner loop, it swaps the positions of the current minimum element and the new minimum element.
  • After completing the inner loop, the minimum element is placed in its correct position in the array.
  • This process continues until the entire array is sorted.
  • Finally, the sorted array is returned.

Flowchart :

Flowchart: Sort an array

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a function to reverse a string.
Next: Write a PHP function that checks if a string is all lower case.

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.