php计算数组中的偶数

时间:2013-08-06 00:20:01

标签: php arrays

所以我正在尝试学习php,找到偶数的代码不输出任何东西,但我似乎无法找到错误,有人能找到我犯了愚蠢错误的地方吗?这是代码:

<?php

/*this sets the array up with the data*/

$myarray = array(1,2,3,4,5,6,7,8,9,10);

/* this is the count to get the total number from my array */

$total = count($myarray);
?>

<h1>Display all even numbers</h1>
<ul>
<?php for ($i=1; $i < total; $i += 2): ?>
<li>The array element value is <?php echo $myarray[$i]; ?>. </li>
<?php endfor; ?>

</ul>

谢谢,如果没有人想发布答案,我理解新问题令人沮丧。

感谢

4 个答案:

答案 0 :(得分:3)

您的代码不是查找偶数。您正在识别它们在数组中的位置,并仅为这些索引打印值。看看这个php片段。

<?php 
$myarray = array(1,2,3,4,5,6,7,8,9,10);
// Array indexes start at 0, not 1.
for ($i = 0; $i < count($myarray); $i++) { 
  echo "Index ", $i, ", value ", $myarray[$i], ": ";
  // A value is even if there's no remainder when you divide it by 2.
  if ($myarray[$i] % 2 == 0) {
    echo "even\n";
  }
  else {
    echo "odd\n";
  }
}
?>

将它放在一个文件中,然后通过php运行它。你应该看到这个。

Index 0, value 1: odd
Index 1, value 2: even
Index 2, value 3: odd
Index 3, value 4: even
Index 4, value 5: odd
Index 5, value 6: even
Index 6, value 7: odd
Index 7, value 8: even
Index 8, value 9: odd
Index 9, value 10: even

此较短版本仅打印偶数值。

<?php 
$myarray = array(1,2,3,4,5,6,7,8,9,10);
for ($i=0; $i < count($myarray); $i++) { 
  if ($myarray[$i] % 2 == 0) {
    echo "Index ", $i, ", value ", $myarray[$i], "\n";
  }
}
?>

Index 1, value 2
Index 3, value 4
Index 5, value 6
Index 7, value 8
Index 9, value 10

答案 1 :(得分:0)

$ for loop遗漏了total变量创建者:

<?php for ($i=1; $i < $total; $i += 2): ?>

答案 2 :(得分:0)

此代码适合您的问题。

 <?php

   $myarray = array(1,2,3,4,5,6,7,8,9,10);
   $total = count($myarray);
   echo "<h1>Display all even numbers</h1>";
                  echo "<ul>";

             foreach($myarray as $rw)
             {
              if(($rw%2) == 0 ){
              echo "<li>".$rw."</li>";
              }
             }
             echo "</ul>";
  ?>

模数运算符%是获取数组中奇数或偶数的最佳方法。

答案 3 :(得分:0)

在php中打印偶数。运行此代码时,$a为20,输出为2,4,6,8,10,12,14,16,18,20,

$a = 20 
  for ($i=0; $i < $a; $i += 2)
            {               
            echo "</n><br>".$i;
            }

像这样出来

2 4 6 8 10 12 14 16 18 20