Home > Article > Backend Development > How to sort the given IP number in PHP
Regarding the sorting problem in PHP, you can first read the "PHP Array Sorting" chapter in the PHP introductory manual. After having a certain understanding of array sorting, this article will introduce to you how to sort all the arrays. Sort by given IP.
Let’s start the theme of this article:
The PHP code is as follows:
<?php function sort_subnets ($x, $y) { $x_arr = explode('.', $x); $y_arr = explode('.', $y); foreach (range(0,3) as $i) { if ( $x_arr[$i] < $y_arr[$i] ) { return -1; } elseif ( $x_arr[$i] > $y_arr[$i] ) { return 1; } } return -1; } $subnet_list = array('192.169.12', '192.167.11', '192.169.14', '192.168.13', '192.167.12', '122.169.15', '192.167.16' ); usort($subnet_list, 'sort_subnets'); var_dump($subnet_list);
The result is:
array (size=7) 0 => string '122.169.15' (length=10) 1 => string '192.167.11' (length=10) 2 => string '192.167.12' (length=10) 3 => string '192.167.16' (length=10) 4 => string '192.168.13' (length=10) 5 => string '192.169.12' (length=10) 6 => string '192.169.14' (length=10)
Here I will introduce to you the functions involved in the above code:
→explode()
The function of the function is to use one string to split another string. And returns an array composed of strings, the syntax is "explode(separator,string,limit)
", the "separator" parameter cannot be an empty string.
参数分别表示: separator:在哪里分割字符串。 string:要分割的字符串。 limit可选:所返回的数组元素的数目。 可能的值有: 大于0:返回包含最多 limit 个元素的数组; 小于0:返回包含除了最后的 -limit 个元素以外的所有元素的数组; 0:会被当做 1, 返回包含一个元素的数组。
→range()
function is used to create an array containing elements in a specified range. The syntax is "range(low,high,step)
"; the The function returns an array containing elements from low to high; if the low parameter is greater than the high parameter, the array created will be from high to low.
→usort()
is used to sort the array using a user-defined comparison function. The syntax is "usort(array,myfunction);
", if successful Returns TRUE, or FALSE if failed.
Finally, I would like to recommend the latest and most comprehensive "PHP Video Tutorial"~ Come and learn!
The above is the detailed content of How to sort the given IP number in PHP. For more information, please follow other related articles on the PHP Chinese website!