In PHP programming, we often need to filter arrays, such as filtering out odd or even numbers in an array. So in PHP, how to implement the function of filtering odd and even numbers in an array? This article will introduce two methods for reference.
1. Use for loop to filter arrays
Using for loop to filter arrays is the most basic method. We can traverse the array, use the if statement to determine whether each element in the array is odd or even, and then save the elements that meet the conditions into a new array.
The following is a sample code:
// 定义原始数组 $arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // 定义新数组 $evenArr = array(); // 存储偶数 $oddArr = array(); // 存储奇数 // 循环遍历数组 for($i = 0; $i < count($arr); $i++){ if($arr[$i] % 2 == 0){ // 判断是否是偶数 $evenArr[] = $arr[$i]; // 存储偶数 } else { $oddArr[] = $arr[$i]; // 存储奇数 } } // 打印输出结果 echo "原数组:"; print_r($arr); echo "<br />"; echo "偶数数组:"; print_r($evenArr); echo "<br />"; echo "奇数数组:"; print_r($oddArr);
Run the above code, the output result is as follows:
原数组:Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 ) 偶数数组:Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 ) 奇数数组:Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 7 [4] => 9 )
You can see that the running result is correct, even numbers and odd numbers have been successfully filtered out .
2. Use PHP built-in functions to filter
PHP provides many built-in functions that can easily operate on arrays, and array filtering is no exception. Among them, the array_filter() function can be used to filter elements of the array. The method of use is as follows:
$newArr = array_filter($arr, function($n){ return ($n % 2 == 0); // 返回为真的元素,即偶数 });
In the above code, we use an anonymous function as the second parameter of the array_filter() function, using $n A variable replaces each element in the array. The return statement in the function body determines whether the element is an even number. If it is an even number, it returns true, otherwise it returns false (that is, no new array is added). Finally, the new array $newArr is the filtered even array.
In addition to using anonymous functions, the array_filter() function can also directly use the preset callback function, such as using the "is_odd" callback function to filter odd numbers:
function is_odd($n){ return ($n % 2 == 1); // 返回为真的元素,即奇数 } $newArr = array_filter($arr, "is_odd");
Using the above two methods, both can be used Easily implement PHP array filtering operations. Of course, the above sample code is only for demonstration, and actual applications may require more flexible operations based on actual conditions.
The above is the detailed content of PHP implements array filtering of odd and even numbers. For more information, please follow other related articles on the PHP Chinese website!