获取PHP语法时出现意外错误';foreach&x27;(T_FOREACH)

获取PHP语法时出现意外错误';foreach&x27;(T_FOREACH),php,foreach,header,Php,Foreach,Header,我正在尝试制作一个foreach代码,自动为我的站点生成标题。这个想法是,当我添加更多的页面时,我可以将它们添加到数组中,它会自动为我更新标题。通常我的同事都在工作,但这是我第一次遇到麻烦。我试了两种方法,两种方法都犯了同样的错误 <link rel="stylesheet" type="text/css" href="css/header.css" /> <?php $page = array("index.php", "about.php"); $names = array

我正在尝试制作一个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>";
    }
}
?>

通常,当PHP返回“unexpected”时,它意味着之前的事情不太正确,如本例所示:


您有
$names=array(“Home”,“About”)
试试这个,并用注释解释:

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

当php返回错误“意外的”it行#xxx时,则表示缺少分号;“it行#xxx-1表示在xxx行的上面

因此,在您的情况下,您缺少foreach循环上方的“半彩色”

$names = array("Home", "About")

和往常一样,您缺少一个分号
$names=array(“Home”,“About”)
@johncode请看,我们的评论值得写在上面。评论被忽略。@Fred ii-至少没有树木受到伤害。@JohnConde为此感谢上帝。我甚至都没意识到,谢谢你。这些都是小事。你应该注意,他们必须确保这两个数组是串联的(如果你要改进他们的代码,那么最好是在一个数组中,键作为名称,值作为href,或者其他什么)同意串联数组,调整我的答案。但是,这不会在锚中输出数字,而是输出$names数组的值,这是一个字符串。。。要么在家里,要么就在家里。是的,累了,对不起-如果循环的
$names
键是串联的,那么它将匹配
$pages
值。