foreach 原來有兩種寫法及表達方法
-第1種是 foreach($arr as $k =>$v){
echo $k.$v;
}; ----------->當中$k為鍵名,$v為鍵值
-第2種為 foreach($arr as $v):
echo $v;
endforeach; ----------->當中$v直接為鍵值。
实例
<?php // store data $headline = 'Movie Today'; $movies = [ 'Strange Things', 'Avengers', 'Star Wars' ]; ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title><?php echo $headline; ?></title> </head> <body> <h2><?php echo $headline; ?></h2> <p>using {} to do a foreach </p> <ul> <?php foreach ( $movies as $k => $v ) { ?> <li><a href="#"><?php echo $v ?></a></li> <?php } ?> </ul> <p>using : to do a foreach</p> <ul> <?php foreach ( $movies as $v ): ?> <li><a href="#"><?php echo $v ?></a></li> <?php endforeach; ?> </ul> <p>------------------------------------------------</p> <form action="" method="post"> <label for="email">Email:</label> <input type="email" id="email" name="email" value="<?php echo isset( $_POST['email'] ) ? $_POST['email'] : ''; ?>"> <label for="password">Password:</label> <input type="password" id="password" name="password" value=""> <button>Login</button> </form> <?php echo '<pre>'; ?> <?php print_r( $_POST ); ?> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例