收到 5 条错误消息 |.PHP


Getting 5 error messages | PHP

<?php
function getLeeftijdsCategorie($leeftijd){
if($leeftijd<18){
    $categorie="kind";
}
elseif($leeftijd>=18&&$leeftijd<65){
    $categorie="volwassen";
}else{
    $categorie="bejaard";
}
return $categorie;
}
//globale array met leeftijden
$aLeeftijden = array(16,17,18,14,22,34,67,58,8,4,55,22,34,45,35);
$aantalKind = 0;
$aantalBejaard = 0;                    
$aantalVolwassen = 0;
for ($x=0; $x <= count($aLeeftijden); $x++) { 
    if (getLeeftijdsCategorie($aLeeftijden[$x]) == 'kind') {
        $aantalKind;
    }
    if (getLeeftijdsCategorie($aLeeftijden[$x]) == 'volwassen') {
        $aantalVolwassen++;
    }
    if (getLeeftijdsCategorie($aLeeftijden[$x]) == 'bejaard') {
        $aantalBejaard++;
    }
}
echo "Aantal kinderen : ".$aantalKind;
echo "<br>Aantal volwassen personen  : ".$aantalVolwassen;
echo "<br>Aantal bejaarden  : ".$aantalBejaard;
    ?>
嗨,我

收到 5 条错误消息,有人可以帮我,我需要得到多少人是儿童等。

我已经尝试了一个多小时,但我真的找不到它。

错误消息是:

PHP 注意:未定义的偏移量:15 在 D:''ICT Opleiding''Applicatieontwikkeling''phpsemester27''PHPPage.php 在第 33 行 PHP 通知:未定义的偏移量:15 在 D:''ICT Opleiding''Applicatieontwikkeling''phpsemester27''PHPPage.php 在第 37 行 PHP 通知:未定义的偏移量:15 在 D:''ICT Opleiding''Applicatieontwikkeling''phpsemester27''PHPPage.php 在第 41 行

谢谢

你"在写入上下文中返回函数值"与以下行相关:

if (getLeeftijdsCategorie($aLeeftijden[$x]) = 'bejaard') {

你必须在==中改变=.

然后,还有一个解析错误:

echo "<br>Aantal bejaarden  : "$aantalBejaard;

必须是:

echo "<br>Aantal bejaarden  : " . $aantalBejaard;
#                               ↑

未定义的失调误差是由于for环结构造成的:

for ($x=0; $x <= count($aLeeftijden); $x++) { 

必须是:

for ($x=0; $x < count($aLeeftijden); $x++) { 

$aLeeftijden计数为 15,但最后一个索引为 14。

尝试以下操作:

// Improved readability    
function getLeeftijdsCategorie( $leeftijd ) {
  if( $leeftijd < 18 ) {
    $categorie = "kind";
  } else if( $leeftijd >= 18 && $leeftijd < 65 ){
    $categorie = "volwassen";
  } else {
    $categorie = "bejaard";
  }
 return $categorie;
}
//globale array met leeftijden
$aLeeftijden = array(16, 17, 18, 14, 22, 34, 67, 58, 8, 4, 55, 22, 34, 45, 35);
$aantalKind = 0;
$aantalBejaard = 0;                    
$aantalVolwassen = 0;
for( $x = 0; $x < count( $aLeeftijden ); $x++ ) { 
    if( getLeeftijdsCategorie( $aLeeftijden[$x] ) == 'kind') {
        $aantalKind++; // Forgot ++
    }
    if( getLeeftijdsCategorie( $aLeeftijden[$x] ) == 'volwassen') {
        $aantalVolwassen++;
    }
    // Forgot =
    if( getLeeftijdsCategorie( $aLeeftijden[$x] ) == 'bejaard') {
        $aantalBejaard++;
    }
}
// Writing strings like this is much less prone to errors 
echo "Aantal kinderen : {$aantalKind}";
echo "<br>Aantal volwassen personen  : {$aantalVolwassen}";
echo "<br>Aantal bejaarden  : {$aantalBejaard}";

不要关闭 PHP,如果你把它包含在其他文件中,如果你在结束 PHP 标签后面有空格,这可能会导致其他错误。