php计算数组中的偶数

php计算数组中的偶数,php,arrays,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); ?>

所以我正在尝试学习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>

显示所有偶数
  • 数组元素值为
谢谢,如果没有人想发布答案,我知道新问题令人沮丧


感谢您在
for循环
for
总计
中缺少
$
变量创建者:

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

您的代码找不到偶数。您将标识它们在数组中的位置,并仅打印这些索引的值。看看这个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 
$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,值2
索引3,值4
索引5,值6
索引7,值8
索引9,值10

此代码适合您的问题

 <?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>";
  ?>


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

在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;
            }
$a=20
对于($i=0;$i<$a;$i+=2)
{               
回声“
”$i; }
像这样出去

二, 4. 6. 8. 10 12 14 16 18
20

您错过了
$
符号表示
总数
此外,您的代码将显示奇数,而不是偶数。您需要将$i从2开始。请记住,您只查看数组中的位置,而不是值。如果你有
数组(3,3,3,5,7,6,6,6,5,1,0)
事情会完全不同。如果您对偶数值感兴趣,则需要检查每个数字。在编程(以及谈论编程问题)时,严格使用术语是值得的。我明白你的观点,这很有意义,$number%2==0是否有效?愚蠢的问题,为什么每个偶数的值都可以被2==0整除?您知道答案在phpDocs中可用吗?谢谢你的帮助,非常感谢。好的,这很有道理,谢谢你帮我清理。
$a = 20 
  for ($i=0; $i < $a; $i += 2)
            {               
            echo "</n><br>".$i;
            }