Home>Article>Backend Development> PHP Algorithm Exercise 9: Convert all even numbers to all odd numbers

PHP Algorithm Exercise 9: Convert all even numbers to all odd numbers

藏色散人
藏色散人 Original
2021-08-13 10:16:11 3933browse

In this article "PHP Algorithm Exercise 8: Determine whether the given three numbers can form a right triangle", I will introduce to you how to judge whether the given three numbers can form a right triangle. Today we continue to start the algorithm exercise series~

The central question of this article is "Write a PHP program to create a new array from a given integer array and move all even numbers before all odd numbers."

Let me first introduce to you the concepts of even numbers and odd numbers:

  • Even numbers are integers that can be divided evenly by 2. Positive even numbers are also called even numbers. If a number is a multiple of 2, then it is an even number and can be expressed as 2n; if not, it is an odd number and can be expressed as 2n 1 (n is an integer), that is, the remainder of an odd number divided by two is one.

  • Odd numbers (odd) refer to integers that are not divisible by 2. The mathematical expression is: 2k 1. Odd numbers can also be divided into positive odd numbers and negative odd numbers.

Let’s get down to business~

The PHP code is as follows:


      

The output result is:

新数组: 2,4,6,3,5,1,5,9,11

You can see that even numbers are in front of odd numbers.

The original array content we gave is[1, 2, 5, 3, 5, 4, 6, 9, 11], and then calculate "$ "numbers[$i] % 2" Whether the result is equal to 0 is also the key formula to determine odd and even numbers. Then determine the odd and even numbers, and then swap the positions.

As for the new array, use theimplode()function to combine the array elements into a string for output.

implode()The function is to return a string composed of array elements.

Finally, I would like to recommend the latest and most comprehensive "PHP Video Tutorial"~ Come and learn!

The above is the detailed content of PHP Algorithm Exercise 9: Convert all even numbers to all odd numbers. 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