PHP入门速成(1)

2019-04-07 19:26:32王振洲

$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.”;

}

您可能感兴趣的文章:

相关文章 大家在看