1. 变量类型
<?php
/*
*字符串 定义在单引号、双引号、定界符中
*单引号:无法解析变量与转义符,运行速度快
*双引号:可以解析变量与转义符
*定界符:可以解析变量与转义符,用于输出长字符串
*
*/
$msg = "开始学习PHP";
$age = '38';
echo '小强今年{$age}岁了。<br>';
// 变量用{}号
echo "小强今年{$age}岁了。<br>";
$msg = "小强今年{$age}岁了。<br>";
echo $msg;
$msg = '第一行 \n 第二行<br>';
echo $msg;
$msg = "第一行 \n 第二行";
echo $msg . "<hr>";
// 定界符
$html = <<<LIST
<ul>
<li>单引号:无法解析变量与转义符,运行速度快</li>
<li>双引号:可以解析变量与转义符</li>
<li>定界符:可以解析变量与转义符,用于输出长字符串</li>
</ul>
LIST;
echo $html;
2. 多维数组遍历
<?PHP
/*
* 遍历数组
* foreach ($arr as $index => $value)
*/
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> 遍历数组</title>
</head>
<body>
<ul>
<?PHP
// 定义数组,模拟导向栏数据库
$nav = [
['id' => 1, 'navName' => '前端学习'],
['id' => 2, 'navName' => '后端学习'],
['id' => 3, 'navName' => '微信学习'],
['id' => 4, 'navName' => '辅助学习'],
['id' => 5, 'navName' => '可视化布局'],
['id' => 6, 'navName' => 'PHP管理系统']
];
// 遍历数组输出导向栏
// 不需要id所以可省略参数
foreach ($nav as $navName) {
echo "<li>{$navName['navName']}</li>";
}
?>
</ul>
</body>
</html>
3. 自定义函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>自定义函数</title>
</head>
<body>
<style>
td {
padding: 15px;
}
</style>
<table>
<thead>
<tr>
<td>商品名称</td>
<td>单位</td>
<td>单价</td>
<td>数量</td>
<td>合计</td>
</tr>
</thead>
<tbody>
<?PHP
// 定义商品
$goods = [
['id' => 1, 'name' => '纯牛奶', 'unit' => '箱', 'price' => 65, 'num' => 2],
['id' => 2, 'name' => '面粉', 'unit' => '5Kg', 'price' => 25, 'num' => 5],
['id' => 3, 'name' => '矿泉水', 'unit' => '件', 'price' => 16, 'num' => 3]
];
// 遍历数组
foreach ($goods as $v) {
$t = total($v['price'], $v['num']);
$html = <<<TABLE
<tr>
<td>{$v['name']}</td>
<td>{$v['unit']}</td>
<td>{$v['price']}</td>
<td>{$v['num']}</td>
<td>{$t}</td>
</tr>
TABLE;
echo $html;
}
// 定义函数计算商品合计价
function total($price, $goodsNum)
{
return $price * $goodsNum;
}
?>
</tbody>
</table>
</body>
</html>