w3resource

PHP Array Exercises : Function to sort subnets


21. Sort Subnets

Write a PHP function to sort subnets.

Sample Solution:

PHP Code:

<?php
// Define a function named 'sort_subnets' for custom sorting of IP subnets
function sort_subnets ($x, $y) {
    // Split IP subnets into arrays of octets
    $x_arr = explode('.', $x);
    $y_arr = explode('.', $y);

    // Iterate through each octet and compare values
    foreach (range(0,3) as $i) {
        // If the current octet in $x is less than the current octet in $y, return -1 (indicating $x comes first)
        if ( $x_arr[$i] < $y_arr[$i] ) {
            return -1;
        }
        // If the current octet in $x is greater than the current octet in $y, return 1 (indicating $y comes first)
        elseif ( $x_arr[$i] > $y_arr[$i] ) {
            return 1;
        }
    }

    // If all octets are equal, return -1 (indicating $x comes first)
    return -1;
}

// Define an array of IP subnets
$subnet_list = array(
    '192.169.12',
    '192.167.11',
    '192.169.14',
    '192.168.13',
    '192.167.12',
    '122.169.15',
    '192.167.16'
);

// Use 'usort' function to sort the array of IP subnets using the 'sort_subnets' custom sorting function
usort($subnet_list, 'sort_subnets');

// Print the sorted array of IP subnets
print_r($subnet_list);
?>

Output:

Array                                                       
(                                                           
    [0] => 122.169.15                                       
    [1] => 192.167.11                                       
    [2] => 192.167.12                                       
    [3] => 192.167.16                                       
    [4] => 192.168.13                                       
    [5] => 192.169.12                                       
    [6] => 192.169.14                                       
) 

Flowchart:

Flowchart: PHP - Sort subnets

For more Practice: Solve these Related Problems:

  • Write a PHP script to sort an array of subnet addresses numerically by converting each subnet to its decimal equivalent.
  • Write a PHP function to compare subnet strings and order them based on network address and mask.
  • Write a PHP program to parse a list of subnet notations, sort them, and then display them in ascending network order.
  • Write a PHP script to implement a custom sort algorithm that arranges subnets by their starting IP addresses using bitwise operations.

Go to:


PREV : Sort Array by Priority List.
NEXT : Sort Array by Day and Username.

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.