Small examples about php arrays and loops

WBOY
Release: 2016-07-25 09:05:14
Original
1035 people have browsed it
  1. //1. Use a loop statement to output any two-dimensional array.

  2. $arr=array(
  3. array(1,2,3,4),
  4. array(5,6,7,8),
  5. array(9,10,11,12),
  6. array(13,14,15 ,16)
  7. );
  8. foreach ($arr as $var){
  9. foreach ($var as $val1){
  10. echo "$val1 ";
  11. }
  12. echo "
    ";
  13. }
  14. echo "
    ";

  15. //2. Use the loop control statement to output the Yang Hui triangle.
  16. function yanghuisanjiao($line){
  17. $sc[][]=array();
  18. $sc[0][0]=1;
  19. for($i=1;$i<=$line;$i++) {
  20. for($j=0;$j<=$i;$j++){
  21. if($j==0 or $i==$j){
  22. $sc[$i][$j]=1 ; //Set the first number and last number of each line to 1
  23. }else{
  24. $sc[$i][$j]=$sc[$i-1][$j-1]+$ sc[$i-1][$j];
  25. }
  26. }
  27. }
  28. foreach ($sc as $value){
  29. foreach($value as $v1){
  30. echo $v1.' ';
  31. }
  32. echo '

    ';

  33. }
  34. }

  35. yanghuisanjiao(5);

  36. echo "
    ";

  37. //3. Use Loop and predefined variables, get multiple parameters. The number of parameters is undetermined.
  38. function avg(){
  39. $ags=func_get_args();
  40. $sum=0;
  41. foreach ($ags as $v){
  42. $sum+=$v;
  43. }
  44. return 'The average is:'.$sum /func_num_args();
  45. }
  46. echo avg(1,2,3,4,5,6,7);

  47. //4. Use a loop to output a two-dimensional array, and Find the sum of the diagonal elements of the rectangle.
  48. function getSum($theCount){
  49. $b=0;
  50. echo '

    ';
  51. echo "";
  52. for($i=1;$i<=$theCount;$i++ ){
  53. echo "
  54. ";
  55. for($j=1;$j<=$theCount;$j++){
  56. if($j==$i || $theCount+1-$i== $j){
  57. echo "
  58. ";
  59. $b=$b+$j;
  60. if($j==$i && $theCount+ 1-$i==$j){
  61. $b=$b+$j;
  62. }
  63. }
  64. else{
  65. echo "
  66. ";
  67. }
  68. }
  69. echo "< /tr>";
  70. }
  71. echo "
  72. $j $j
    ";
  73. echo "The sum of the diagonal elements is:".$b;
  74. }
  75. getSum(6);
  76. ?>

  77. Copy codeYou may also like: php example of array recursive sum


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!