得到PHP语法错误意外'foreach'(T_FOREACH)

时间:2014-12-03 02:17:21

标签: php foreach header

我正在尝试制作一个自动为我的网站制作标题的foreach代码。我的想法是,当我添加更多页面时,我可以将它们添加到数组中,它会自动为我更新标题。通常我的foreach工作,但我第一次遇到麻烦。我尝试了两种方法,这两种方式都会产生同样的错误。

<link rel="stylesheet" type="text/css" href="css/header.css" />
<?php
$page = array("index.php", "about.php");
$names = array("Home", "About")


foreach($names as $name){
    echo "<a href=$page> $name </a>";
}

?>

<link rel="stylesheet" type="text/css" href="css/header.css" />
<?php
$page = array("index.php", "about.php");
$names = array("Home", "About")

foreach($page as $pages){
    foreach($names as $name){
        echo "<a href=$pages> $name </a>";
    }
}
?>

3 个答案:

答案 0 :(得分:9)

通常当PHP返回“意外”时,它意味着它不太正确,就像这种情况一样:

你有$names = array("Home", "About")&lt; - 没有半冒号来结束这一行,所以下一行foreach 意外,因为它“期待”一个{ {1}}

看起来你已经将错误(缺少半冒号)复制/粘贴到代码中的其他地方

答案 1 :(得分:2)

当php返回错误“意外”它行#xx时,则表示你缺少半冒号“;”它的行#xxx-1意味着高于xxx行的行

答案 2 :(得分:0)

试试这个,并附上评论解释:

<head>
    <link rel="stylesheet" type="text/css" href="css/header.css" />
</head>
<body>
<?php
$page = array("index.php", "about.php");
$names = array("Home", "About"); // Fixed semicolon

// Added the key before the foreach. This allows us to reference which number in we are.
foreach($names as $key => $name)
{
    // Added the key to the page array variable to specify the right page.
    echo "<a href=".$page[$key].">".$name."</a>";
}?>
</body>

要进一步简化数组键的使用,请尝试以下方法:

<?php
// Define page names as key and url as value.
$pages = array("Home" => "index.php", "About" => "about.php");

// Added the key before the foreach as url this time
foreach($pages as $name => $url)
{
    // Added the key to the page array variable to specify the right page.
    echo "<a href=".$url.">".$name."</a>";
}?>