for/foreach循環中的變量是否具有局部範圍?如果是這樣,我該如何使其成爲全球?PHP for; foreach變量範圍
page.php文件:
<?php
$title = "2";
$menu[0] = "1";
$menu[1] = "2";
$menu[2] = "3";
$menu[3] = "4";
$menu[4] = "5";
$menu[5] = "6";
$menu[6] = "7";
$menu[7] = "8";
foreach ($menu as $value){
if ($title == $value){
$active = "active";
echo "if " . $active. $title . $menu[$x] ." <br /><br />";
}
else {
$active = "";
echo "else " . $active. $title . $menu[$x] ." <br /><br />";
}}
include "header.php";
foreach ($menu as $value) {
var_dump($active);
echo "$value <br>";
}
include "header.php";
?>
<!-- begin page content -->
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
<!-- end page content -->
<?php
include "footer.php";
?>
從本質上講,我有這條線在header.php中:
<li class="mainNav <?php echo $active; ?>" style="z-index:8">
<a href="http://www.com"><?php echo $menu[0]; ?></a></li>
我想要列表有類= 「mainNav活躍」,如果它是該頁面和class =「mainNav」如果不是。
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!
所以我從@urfusion建議創建一個功能。現在page.php文件:
<?php
$title = "2";
$menu[0] = "1";
$menu[1] = "2";
$menu[2] = "3";
$menu[3] = "4";
$menu[4] = "5";
$menu[5] = "6";
$menu[6] = "7";
$menu[7] = "8;
?>
<?php
function mainNav($menu) {
foreach ($menu as $value){
if ($title == $value){
$active = "active";
echo "if " . $active. $title . $menu[$x] . " <br /><br />";
}
else {
$active = " ";
echo "else " . $active. $title . $menu[$x] . " <br /><br />";
}
echo "function" . $active . $value;
return $active;
}
}
include "header.php";
?>
<!-- begin page content -->
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
<!-- end page content -->
<?php
include "footer.php";
?>
而且header.php文件:
<li class="mainNav <?php mainNav(); ?>" style="z-index:8">
<a href="http://www.com"><?php echo $menu[1]; ?></a></li>
還是什麼都沒有,現在我似乎失去了回波語句的輸出...
在foreach循環之前初始化'$ active' – urfusion
「for/foreach循環中的變量是否有本地作用域?」 - 循環,開關/案例,try-catch塊等不構成在PHP中的範圍。見https://3v4l.org/WjX5Q – VolkerK
我不知道你在做什麼。第二個foreach完全拋棄我! –