Home >Daily Programming >PHP Knowledge >How to implement odd-even sorting of array elements in PHP? (Pictures + Videos)

How to implement odd-even sorting of array elements in PHP? (Pictures + Videos)

藏色散人
藏色散人Original
2018-10-13 13:52:243808browse

This article mainly introduces specific methods to implement odd-even sorting of array elements in PHP.

PHP implements odd-even sorting of elements in an array. It is a relatively common interview question during our PHP interview process. Of course, we will also encounter array-related sorting issues in our usual project development process.

Below we will use a simple code example to introduce to you how to implement odd-even sorting of elements in a PHP array.

First of all, everyone must be familiar with the concept of odd and even numbers. It is nothing more than that one is not divisible by 2 and the other is divisible by 2.

Then the complete code example to implement parity sorting of array elements is as follows:

<?php

// 获取数组中的奇数
function odd($var)
{
    return($var % 2);
}
// 获取数组中的偶数
function even($var)
{
    return (!($var % 2));
}

$array = array(1,2,3,4,5,6,7,8,9,10);
print_r(array_filter($array, "odd"));
echo "<br>";
print_r(array_filter($array, "even"));

The final result of parity sorting of array elements is as shown below:

How to implement odd-even sorting of array elements in PHP? (Pictures + Videos)

Here we first define two methods odd/even to get the odd and even numbers in the array, and then mainly use the array_filter function.

array_filter function: Use callback function to filter units in the array. The parameter represents the array to be looped.

Description: In this example, each value in the array array is passed to the odd/even function in turn. If the odd/even function returns true, the current value of the array array will be included in the returned result array. The key names of the array remain unchanged.

This article is an introduction to the method of implementing parity sorting of array elements in PHP. I hope it will be helpful to friends in need!

If you want to know more about PHP, you can follow the PHP Chinese website PHP Video Tutorial, everyone is welcome to refer to and learn!

The above is the detailed content of How to implement odd-even sorting of array elements in PHP? (Pictures + Videos). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn