Home  >  Article  >  Backend Development  >  PHP algorithm example sharing

PHP algorithm example sharing

WBOY
WBOYOriginal
2016-07-25 08:44:371171browse

Only print 0

 The specific number is determined by the input parameter n

 If n=5, print 00000

  1. $n = $_GET['n'];
  2. for ($i=0; $i < $n; $i++) {
  3. echo "0";
  4. }
  5. ? >
Copy code

Print a line 0101010101010101010101

 The specific number is determined by the input parameter n

 For example test.php?n=3 print 010

  1. $n = $_GET['n'];
  2. for ($i=0; $i < $n; $i++) {
  3. if ($i % 2 ==0 ) {
  4. echo "0";
  5. } else{
  6. echo "1";
  7. }
  8. }
  9. ?>
Copy code

Achieve 1 00 111 0000 11111

 for if implementation

  1. for ($i = 0; $i < 10; $i++) {
  2. for ($j = 0; $j <= $i; $j++) {
  3. if ($i % 2 == 0) {
  4. echo '0';
  5. } else {
  6. echo '1';
  7. }
  8. }
  9. echo '
    ';
  10. }
  11. ?>
Copy code

 For switch implementation

  1. for ($i = 0; $i < 10; $i++) {
  2. for ($j = 0; $j <= $i; $j++) {
  3. switch ($j % 2) {
  4. case '0':
  5. echo "0";
  6. break;
  7. case '1':
  8. echo "1";
  9. break;
  10. }
  11. }
  12. echo '
    ';
  13. }
  14. ?>
Copy code

 while if implementation

 while switch implementation

  1. $i = 0;
  2. while ($i < 10) {
  3. $j = 0;
  4. while ($j <= $i) {
  5. switch ($i % 2) {
  6. case 0:
  7. echo '0';
  8. break;
  9. case 1:
  10. echo '1';
  11. break;
  12. }
  13. $j++;
  14. }
  15. echo '
    ';
  16. $ i++;
  17. }
  18. ?>
Copy code

Achieve 0 01 010 0101……

Achieve 0 01 012 0123 3210 210 10 0

Make a calculator

 For example, test.php?a=1&b=2&operator=jia outputs 3

 For example, test.php?a=5&b=2&operator=jian outputs 3

 For example, test.php?a=2&b=5&operator=cheng outputs 10

 For example, test.php?a=6&b=3&operator=chu outputs 2

  1. $a = $_GET['a'];
  2. $b = $_GET['b'];
  3. $operator = $_GET['operator'];
  4. function calculate($ a,$b,$operator) {
  5. switch ($operator) {
  6. case 'jia':
  7. $result = $a + $b;
  8. return $result;
  9. break;
  10. case 'jian':
  11. $result = $a - $b;
  12. return $result;
  13. break;
  14. case 'cheng':
  15. $result = $a * $b;
  16. return $result;
  17. break;
  18. case 'chu':
  19. $result = $a / $b;
  20. return $result;
  21. break;
  22. }
  23. }
  24. echo calculate($a,$b,$operator);
  25. ?>
Copy code

The above is the entire content of this article, I hope you all like it.

php


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