Lab3.1 - Arrays in PHP
<?php
// put your code here
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8);
$numbers = [1, 2, 3, 4, 5, 6, 7, 8];
array_push($numbers, 9);
$numbers[] = 10;
$numbers[3] = 104;
echo"Contents of integer array<br/>";
for ($index = 0; $index < count($numbers); $index++) {
echo $numbers[$index] . " ";
}
echo "<br/>";
echo"Contents of integer array using foreach<br/>";
foreach ($numbers as $value) {
echo"$value ";
}
echo"<br/>";
array_pop($numbers);
echo"Contents of integer array using print_r function<br/>";
print_r($numbers);
echo"<br/>";
echo"Contents of integer array using var_dump function<br/>";
var_dump($numbers);
echo"<br/>";
$numbers = [];
for ($index = 0; $index < 6; $index++) {
$numbers[] = rand(1, 45);
}
echo "Contents of tattslotto numbers array<br/>";
foreach ($numbers as $value) {
echo"$value ";
}
echo "<br/>";
sort($numbers);
echo "Contents of tattslotto numbers array after sorting<br/>";
foreach ($numbers as $value) {
echo "$value ";
}
echo "<br/>";
?>
运行结果:
创建数组方法:
- $numbers = array(1, 2, 3, 4, 5, 6, 7, 8);
- $numbers = [1, 2, 3, 4, 5, 6, 7, 8];
添加数组元素:
- array_push($numbers, 9);
- $numbers[] = 10;
输出数组:
- for循环
- foreach函数
- print_r()
- var_dump()
Lab3.2 - Associative Arrays in PHP
<?php
// put your code here
$game = ["title" => "League of lengends",
"author" => "Riot Games",
"ranking" => 1,
"players" => 11500000];
echo "Display contents of game: <br/>";
foreach ($game as $key => $value) {
echo"$key : $value <br/>";
}
echo "<br/>";
$games = [
["title" => "League of lengends",
"author" => "Riot Games",
"ranking" => 1,
"players" => 11500000],
["title" => "Counter Strike Go",
"author" => "Valve",
"ranking" => 2,
"players" => 6.88],
["title" => "Fallout 4",
"author" => "Bethesda Softworks",
"ranking" => 3,
"players" => 5.78],
["title" => "Dota 2",
"author" => "Blizzard/Valve",
"ranking" => 4,
"players" => 5.09],
["title" => "World of Warcraft",
"author" => "Blizzard",
"ranking" => 5,
"players" => 4.82]
];
echo"Displaying the contents of games <br/><br/>";
foreach ($games as $game) {
foreach ($game as $key => $value) {
echo "$key : $value <br/>";
}
echo"<br/>";
}
?>
运行结果:
Lab3.3 - Super Global Arrays in PHP
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
// put your code here
$ans = rand(0, 100);
foreach ($_GET as $value);
if (empty($_GET)) {
echo"No number entered in the URL";
} else {
if ($ans == $value) {
echo"Correct! You have guessed the number $ans </br>";
} else {
echo"Try again! The number is $ans </br>";
}
}
?>
</body>
</html>
运行结果: