PHP 中如何在不使用循环的情况下从数组中分离奇数和偶数元素

假设有一个包含 n 个元素的数组,任务是根据它们是偶数还是奇数将这些元素从数组中分离出来。
换句话说,需要在不使用任何循环或者遍历数组的初始状态的情况下打印奇数数组和偶数数组。

使用 array_filter() 和 array_values()

如果我们想避免使用循环来执行上述任务,那么我们需要使用内置的 PHP 函数,例如 array_filter() 和 array_values()。

此外,请考虑到 array_filter() 仅使用索引值过滤奇数/偶数索引元素。
使用array_filter()后,奇数数组的索引为1、3、5,偶数数组的索引为0、2、4.

首先,让我们看看算法的样子:

  • 过滤元素:
  • 通过 array_filter() 过滤奇数元素。
  • 通过 array_filter() 过滤偶数元素。
  • 重新索引数组:
  • 使用 array_values() 重新索引奇数数组。
  • 使用 array_values() 重新索引偶数数组。
  • 打印奇数/偶数数组。

上述算法的说明如下:

<?php
//PHP program to separate odd-even indexed 
//elements of an array 
//input array 
$input = array(
  4,
  3,
  6,
  5,
  8,
  7,
  2
);
//comparator function to filter odd elements 
function oddCmp($input)
{
  return ($input & 1);
}
//comparator function to filter odd elements 
function evenCmp($input)
{
  return !($input & 1);
}
//filter odd-index elements 
$odd = array_filter($input, "oddCmp");
//filter even-index elements 
$even = array_filter($input, "evenCmp");
//re-index odd array by use of array_values() 
$odd = array_values(array_filter($odd));
//re-index even array by use of array_values() 
$even = array_values(array_filter($even));
//print odd-indexed array 
print "Odd array :\n";
print_r($odd);
//print even-indexed array 
print "\nEven array :\n";
print_r($even);
?>

输出如下:

Odd array :
Array
(
    [0] => 3
    [1] => 5
    [2] => 7
)
Even array :
Array
(
    [0] => 4
    [1] => 6
    [2] => 8
    [3] => 2
)
日期:2020-06-02 22:15:53 来源:oir作者:oir