基本語法
<?php
echo “welcome to my blog!”;
?>
顯示結果爲“welcome to my blog!”。
PHP中,所有的變量都以標識“$”開頭。我們可以對上述代碼做如下改動:
PHP中使用“.”符號連接不同的字符串,而其它的算術運算符則繼承了流行編程語言的風格。舉例如下:
<?php
$greeting = “Hello!”;
$num = 3 + 2;
$num++;
echo “$greeting $num people!”;
?>
顯示結果爲“Hello!6 people!”。
PHP對各種運算符及運算規則都有一套完整的規定,如果用戶具有C或C++語言的編程背景的話,可以發現一切都得心應手。
與Perl語言一樣,在PHP中,如果在雙引號包含的字符串中含有變量的話,該變量將用相應的變量值替換;如果字符串被單引號包含,則不做替換。例如:
<?php
$name = ‘PETER’;
$greeting_1 = “Hello, $name!”;
$greeting_2 = ‘Hello, $name!’;
echo “$greeting_1n”;
echo “$greeting_2n”;
?>
顯示結果爲:
Hello, PETER!
Hello, $name!
(注:上述代碼中的“n”爲換行符,只能在雙引號字符串下使用)
B. 變量
PHP允許用戶象使用常規變量一樣使用環境變量。例如,在頁面http://www.nba.com/scores/index.html中包含如下代碼:
<?php
echo “[$REQUEST_URI]”;
?>
則輸出結果爲[/scores/index.html]
C. 數組
用戶在使用PHP創建數組時,可以把數組索引(包括常規索引或關聯索引)加入方括號中。例如:
$fruit[0] = ‘banana’;
$fruit[1] = ‘apple’;
$favorites['animal'] = ‘tiger’;
$favorites['sports'] = ‘basketball’;
如果用戶在向數組賦值時不指明數組下標,PHP將自動把該對象加入到數組末尾。例如對於上述$fruit數組可以用以下方式賦值而保持結果不變,
$fruit[] = ‘banana’;
$fruit[] = ‘apple’;
同樣,在PHP中,用戶還可以根據需要建立多維數組。例如:
$people[‘David’][‘shirt’] = ‘blue’;
$people[‘David’][‘car’] = ‘red’;
$people[‘Adam’][‘shirt’] = ‘white’;
$people[‘Adam’][‘car’] = ‘silver’;
在PHP中,用戶還可以使用array()函數快速建立數組。例如:
$fruit = array(‘banana’,‘apple’);
$favorites = array(‘animal’ => ‘tiger’, ‘sports’ => ‘basketball’);
或者使用array()函數創建多維數組:
$people = array (‘David’ => array(‘shirt’ => ‘blue’,’car’ => ‘red’),
‘Adam’ => array(‘shirt’ => ‘white’,‘car’ => ‘silver’));
此外,PHP還提供了內置函數count()用於計算數組中的元素數量。例如:
$fruit = array(‘banana’, ‘apple’);
print count($fruit);
顯示結果爲2。
D. 結構控制
在PHP中,用戶可以使用“for”或“while”等的循環結構語句。例如:
for ($i = 4; $i < 8; $i++) {
print “I have eaten $i apples today.n”; }
或
$i = 4; while ($i < 8) {
print “I have eaten $i apples today.n”;
$i++;
}
返回結果爲:
I have eaten 4 apples today.
I have eaten 5 apples today.
I have eaten 6 apples today.
I have eaten 7 apples today.
此外,用戶還可以使用“if”和“elseif”等的選擇性結構語句。例如:
if ($user_count > 200) {
print “The site is busy right now!”;}
elseif ($user_count > 100) {
print “The site is active right now!”;
else {
print “The site is idle - only $user_count user logged on.”;
}