Home php教程 php手册 PHP基础学习之语法

PHP基础学习之语法

Jun 06, 2016 pm 08:00 PM
php Base start Finish Script grammar

1、PHP 的脚本块以 ?php 开始,以 ? 结束。 ?php? 2、向浏览器输出文本可以用echo或者print,注意PHP中的每一句脚本都要以分号;结束,用法如下: ?phpecho hellobr/;print(world);? 3、PHP的注释和c、java类,可以用//或者/**/,如下所示: ?php//echo hello

1、PHP 的脚本块以 开始,以 ?> 结束。

<?php ?>
Copy after login

2、向浏览器输出文本可以用echo或者print,注意PHP中的每一句脚本都要以分号";"结束,用法如下:
<?php echo "hello<br/>";
	print("world");
?>
Copy after login

3、PHP的注释和c、java类似,可以用//或者/**/,如下所示:
<?php //echo "hello<br/>";
	/*print("world");*/
?>
Copy after login

4、PHP中的变量以$开头,且不需要指定变量的类型,用法如下:
<?php $name = "zhangsan";
	echo $name;
	
	echo "<br/>";
	
	$age = 20;
	echo $age;
	
	echo "<br>";
	
	echo $name . " is " . $age . " years old.";
?>
Copy after login
上面的脚本在浏览器中输出如下:

PHP基础学习之语法
注意:PHP中连接字符串用的是点"."

5、求字符串长度函数strlen(),该函数返回的字符串长度值,如下所示:

<?php $str = "hello, world!";
	echo strlen($str);
?>
Copy after login
上面的脚本在浏览器中输出结果为:13

6、strpos($str1, $str2)函数,该函数有两个字符串类型的参数,用于检索str2在str1中的起始位置,用法如下:

<?php $str1 = "hello, world!";
	$str2 = "o";
	$pos = strpos($str1, $str2);
	echo $pos;
?>
Copy after login

上面的脚本在浏览器中输出结果为:4,如果没有在str1中匹配到str2,则浏览器不会有输出

7、PHP中的运算符与java、c中的运算符都差不多,需要注意的是,PHP中比较两个字符串是否相等,直接用"=="就行了,测试代码如下:

<?php function equals($str1, $str2){
		if($str1 == $str2){
			echo "equals<br/>";
		}else{
			echo "not equals<br>";
		}
	}
	$str1 = "hello";
	$str2 = "hello2";
	$str3 = "hello";
	equals($str1, $str2);
	equals($str1, $str3);
?>
Copy after login

上面的脚本定义了一个函数,名为equals,有两个参数,在函数体内比较如果两个参数相等,则输出equals,否则输出not equals,上面的代码在浏览器中输出如下图所示:

PHP基础学习之语法

注意PHP中函数的定义,是以function开头,加上函数名和括号里的参数名

8、PHP中的条件语句,类似于java里的条件语句,不过PHP中加了关键字elseif,用法如下:

<?php $a = 3;
	$b = 2;
	if($a > $b){
		echo "a > b";
	}elseif($a 
Copy after login
9、PHP中的switch语句,用法和java类似,而且PHP中的switch支持字符串,用法如下:
<?php $a = "c";
switch ($a) {
	case "a" :
		echo "a";
		break;
	case "b" :
		echo "b";
		break;
	case "c" :
		echo "c";
		break;
}
?>
Copy after login

10、PHP中数组的使用:

创建数组有两种方法,如下面的脚本所示:

<?php //第一种创建数组的方式
	$names = array("tom", "jack", "herry");
	foreach($names as $name){
		echo $name . "<br/>";
	}
	
	//第二种创建数组的方式
	$colors[0] = "red";
	$colors[1] = "blue";
	$colors[2] = "green";
	foreach($colors as $color){
		echo $color . "<br>";
	}
	
?>
Copy after login

上面的脚本在浏览器中输出为:

PHP基础学习之语法

注意上面用foreach循环输出了数组里的内容


PHP中的数组有一种用法,特别类似java里的Map,即可以按键值对的形式存储数组,看下面的脚本:
<?php $names = array("tom" => 23, "jack" => 18, "herry" => 21);
	echo $names["jack"];
?>
Copy after login
上面的脚本中,我们为不同姓名的人分配了一个年龄,然后可以根据姓名取出他的年龄

11、PHP函数在之前已有用到,PHP的函数可以带参数,可以有返回值,示例代码如下:
<?php function add($num1, $num2){
		return $num1 + $num2;
	}
	echo "3 + 4 = " . add(3, 4);
?>
Copy after login

12、PHP处理表单提交的数据,主要用PHP内置的变量$_GET和$_POST,从名字上就可以看出,$_GET用于接收表单以GET方式提交的数据,$_POST用于接收表单以POST方式提交的数据,我们新建两个文件,分别为login.php和result.php,将login.php中的表单数据提交给result.php,然后显示数据,下面是脚本:

login.php脚本如下:

Copy after login

result.php脚本如下:
<?php $username = $_POST["username"];
	echo "welcome user : " . $username;
?>
Copy after login

在浏览器中访问的结果如下:

PHP基础学习之语法PHP基础学习之语法

如果表单中的method为get,则result.php中需要用$_GET["username"]来取得输入的值

PHP中的内置变量$_REQUEST可以取到get或post方式提交的表单数据

13、PHP格式化时间的date()函数

PHP的date()函数有两个参数,第一个参数是格式化的格式,为必须参数,第二个是时间戳,为可选参数,

date() 函数的第一个参数规定了如何格式化日期/时间。它使用字母来表示日期和时间的格式。这里列出了一些可用的字母:

  • d - 月中的天 (01-31)
  • m - 当前月,以数字计 (01-12)
  • Y - 当前的年(四位数) 
下面的代码用于输出当前的年月日:
<?php echo date("Y/m/d");
?>
Copy after login
使用mktime()函数可以返回一个时间戳,mktime()函数的参数比较多,如下:
mktime(hour,minute,second,month,day,year)
Copy after login
下面的代码输出明天的日期:
<?php $tom = mktime(0, 0, 0, date("m"), date("d") + 1, date("Y"));
	echo date("Y/m/d", $tom);
?>
Copy after login
这里用date("m")获取当前的月份,date("d")获取当前的天,date("Y")获取当前的年份

14、PHP引入其他文件

PHP中引入其他文件有两种方式,使用include或require,这两个函数的不同之处在于,他们对错误的处理方式不同,include如果引入了一个不存在的页面,会在页面上显示警告信息,但是include之后的脚本会继续执行,而使用require引入一个不存在的页面,页面上会显示警告信息,且require后的脚本不会执行

15、PHP操作文件

下面的脚本是使用PHP按行读取并输出文件内容:

<?php $file = fopen("data.txt", "r") or exit("open file error");
	while(!feof($file)){//按行读取文件内容
		echo fgets($file) . "<br/>"; 
	}
?>
Copy after login
PHP使用fopen函数打开一个文件,第一个参数指定文件路径,第二个参数指定文件的打开方式,有如下几种打开方式:

模式 描述
r 只读。在文件的开头开始。
r+ 读/写。在文件的开头开始。
w 只写。打开并清空文件的内容;如果文件不存在,则创建新文件。
w+ 读/写。打开并清空文件的内容;如果文件不存在,则创建新文件。
a 追加。打开并向文件文件的末端进行写操作,如果文件不存在,则创建新文件。
a+ 读/追加。通过向文件末端写内容,来保持文件内容。
x 只写。创建新文件。如果文件以存在,则返回 FALSE。
x+

读/写。创建新文件。如果文件已存在,则返回 FALSE 和一个错误。

注释:如果 fopen() 无法打开指定文件,则返回 0 (false)。


feof()函数用于判断是否读到文件末尾,fgets()函数用于读取文件的一行,读取后文件指针会自动跳到下一行,逐字符地读取文件需要使用函数fgetc(),关闭文件则使用函数fclose()

今天的学习记录就到这里。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles