php 入门示例_最好PHP示例

php 入门示例

PHP is a server-side scripting language created in 1995 by Rasmus Lerdorf.

PHP是Rasmus Lerdorf于1995年创建的服务器端脚本语言。

PHP is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

PHP是一种广泛使用的开源通用脚本语言,特别适合于Web开发,并且可以嵌入HTML中。

PHP的作用是什么? (What is PHP used for?)

As of October 2018, PHP is used on 80% of websites whose server-side language is known. It is typically used on websites to generate web page content dynamically. Use-cases include:

截至2018年10月,PHP已在80%已知服务器端语言的网站上使用。 它通常用于网站上以动态生成网页内容。 用例包括:

  • Websites and web applications (server-side scripting)

    网站和Web应用程序(服务器端脚本)
  • Command line scripting

    命令行脚本
  • Desktop (GUI) applications

    桌面(GUI)应用程序

Typically, it is used in the first form to generate web page content dynamically. For example, if you have a blog website, you might write some PHP scripts to retrieve your blog posts from a database and display them. Other uses for PHP scripts include:

通常,它以第一种形式用于动态生成网页内容。 例如,如果您有一个博客网站,则可以编写一些PHP脚本来从数据库检索博客文章并显示它们。 PHP脚本的其他用途包括:

  • Processing and saving user input from form data

    处理和保存来自表单数据的用户输入
  • Setting and working with website cookies

    设置和使用网站cookie
  • Restricting access to certain pages of your website

    限制访问网站的某些页面

The largest Social Networking Platform, Facebook is written using PHP

最大的社交网络平台, Facebook是使用PHP编写的

PHP如何工作? (How does PHP work?)

All PHP code is executed on a web server only, not on your local computer. For example, if you complete a form on a website and submit it, or click a link to a web page written in PHP, no actual PHP code runs on your computer. Instead, the form data or request for the web page gets sent to a web server to be processed by the PHP scripts. The web server then sends the processed HTML back to you (which is where 'Hypertext Preprocessor' in the name comes from), and your web browser displays the results. For this reason, you cannot see the PHP code of a website, only the resulting HTML that the PHP scripts have produced.

所有PHP代码仅在Web服务器上执行,而不在本地计算机上执行。 例如,如果您在网站上填写表格并提交,或者单击指向用PHP编写的网页的链接,则计算机上不会运行任何实际PHP代码。 而是将表单数据或网页请求发送到Web服务器,以由PHP脚本处理。 然后,Web服务器将处理后HTML发送回给您(这就是名称中的“超文本预处理器”的来源),然后您的Web浏览器将显示结果。 因此,您看不到网站PHP代码,只能看到PHP脚本生成的结果HTML。

This is illustrated below:

如下图所示:

PHP is an interpreted language. This means that when you make changes to your source code you can immediately test these changes, without first needing to compile your source code into binary form. Skipping the compilation step makes the development process much faster.

PHP是一种解释性语言。 这意味着,当您对源代码进行更改时,您可以立即测试这些更改,而无需首先将源代码编译为二进制形式。 跳过编译步骤可使开发过程更快。

PHP code is enclosed between the <?php and ?> tags and can then be embedded into HTML.

PHP代码包含在<?php?>标记之间,然后可以嵌入到HTML中。

安装 (Installation)

PHP can be installed with or without a web server.

PHP可以安装Web服务器,也可以不安装Web服务器。

GNU / Linux (GNU/Linux)

On Debian based GNU/Linux distros, you can install by :

在基于Debian的GNU / Linux发行版上,可以通过以下方式安装:

sudo apt install php

On Centos 6 or 7 you can install by :

在Centos 6或7上,您可以通过以下方式安装:

sudo yum install php

After installing you can run any PHP files by simply doing this in terminal :

安装后,只需在终端中执行以下操作即可运行任何PHP文件:

php file.php

You can also install a localhost server to run PHP websites. For installing Apache Web Server :

您也可以安装本地主机服务器来运行PHP网站。 要安装Apache Web Server:

sudo apt install apache2 libapache2-mod-php

Or you can also install PHP, MySQL & Web-server all by installing

或者您也可以通过安装PHP,MySQL和Web服务器来全部安装

XAMPP (free and open-source cross-platform web server solution stack package) or similar packages like WAMP

XAMPP (免费和开放源代码的跨平台Web服务器解决方案堆栈软件包)或类似的软件包,例如WAMP

PHP框架 (PHP Frameworks)

Since writing the whole code for a website is not really practical/feasible for most projects, most developers tend to use frameworks for the web development. The advantage of using a framework is that

由于对于大多数项目而言,为网站编写整个代码并不实际/可行,因此大多数开发人员倾向于使用框架进行Web开发。 使用框架的优点是

  • You don't have to reinvent the wheel every time you create a project, a lot of the nuances are already taken care for you

    您不必在每次创建项目时都重新发明轮子,许多细微差别已经为您照顾好了
  • They are usually well-structured so that it helps in the separation of concerns

    它们通常结构合理,因此有助于分离关注点
  • Most frameworks tend the follow the best practices of the language

    大多数框架倾向于遵循语言的最佳实践
  • A lot of them follow the MVC (Model-View-Controller) pattern so that it separates the presentation layer from logic

    他们中的许多人遵循MVC(模型-视图-控制器)模式,从而将表示层与逻辑分离

基本语法 (Basic Syntax)

PHP scripts can be placed anywhere in a document, and always start with <?php and end with ?>. Also, PHP statements end with a semicolon (;).

PHP脚本可以放置在文档中的任何位置,并且始终以<?php开头并以?>结尾。 另外,PHP语句以分号(;)结尾。

Here's a simple script that uses the built-in echo function to output the text "The Best PHP Examples" to the page:

这是一个简单的脚本,该脚本使用内置的echo函数将文本“ The Best PHP Examples”输出到页面:

<!DOCTYPE html>
<html>
<body>

<h1>Developer News</h1>

<?php echo "The Best PHP Examples"; ?>

</body>
</html>

The output of that would be:

其输出将是:

Developer News

The Best PHP Examples

注释 (Comments)

PHP supports several ways of commenting:

PHP支持多种注释方式:

  • Single-line comments:

    单行注释:
  • Multi-line comments:

    多行注释:
<?php
  // This is a single-line comment
  
  # You can also make single-line comments like this
?>
<?php
/*
This comment block spans
over multiple 
lines
*/
?>

区分大小写 (Case Sensitivity)

All keywords, classes, and functions are NOT case sensitive.

所有关键字,类和函数都不区分大小写。

In the example below, all three echo statements are valid:

在下面的示例中,所有三个echo语句均有效:

<?php
ECHO "Hello!<br>";
echo "Welcome to Developer News<br>";
EcHo "Enjoy all of the ad-free articles<br>";
?>

However, all variable names are case sensitive. In the example below, only the first statement is valid and will display the value of the $name variable. $NAME and $NaMe are both treated as different variables:

但是,所有变量名都区分大小写。 在下面的示例中,只有第一条语句有效,并且将显示$name变量的值。 $NAME$NaMe都被视为不同的变量:

<?php
$name = "Quincy";
echo "Hi! My name is " . $name . "<br>";
echo "Hi! My name is " . $NAME . "<br>";
echo "Hi! My name is " . $NaMe . "<br>";
?>

变数 (Variables)

Variables are the main way to store information in a PHP program.

变量是在PHP程序中存储信息的主要方法。

All variables in PHP start with a leading dollar sign like $variable_name. To assign a variable, use the = operator, with the name of the variable on the left and the expression to be evaluated on the right.

PHP中的所有变量都以前导美元符号开头,例如$variable_name 。 要分配变量,请使用=运算符,在变量的名称在左侧,要计算的表达式在右侧。

Syntax:

句法:

<?php
// Assign the value "Hello!" to the variable "greeting"
$greeting = "Hello!";
// Assign the value 8 to the variable "month"
$month = 8;
// Assign the value 2019 to the variable "year"
$year = 2019;
?>

PHP变量规则 (Rules for PHP variables)

  • Variable declarations starts with $, followed by the name of the variable

    变量声明以$开头,后跟变量名

  • Variable names can only start with an upper or lowercase letter or an underscore (_)

    变量名称只能以大写或小写字母或下划线( _ )开头

  • Variable names can only contain letters, numbers, or underscores (A-z, 0-9, and _). Other special characters like + - % ( ) . & are invalid

    变量名称只能包含字母,数字或下划线(Az,0-9和_ )。 其他特殊字符,例如+ - % ( ) . & + - % ( ) . &无效

  • Variable names are case sensitive

    变量名称区分大小写

Some examples of allowed variable names:

允许的变量名称的一些示例:

  • $my_variable

    $ my_variable
  • $anotherVariable

    $ anotherVariable
  • $the2ndVariable

    $ the2ndVariable

预定义变量 (Predefined Variables)

PHP has several special keywords that, while they are "valid" variable names, cannot be used for your variables. The reason for this is that the language itself has already defined those variables and they have are used for special purposes. Several examples are listed below, for a complete list see the PHP documentation site.

PHP有几个特殊的关键字,尽管它们是“有效的”变量名,但不能用于您的变量。 原因是该语言本身已经定义了这些变量,并且已将它们用于特殊目的。 下面列出了几个示例,有关完整列表,请参见PHP文档站点

  • $this

    $this

  • $_GET

    $_GET

  • $_POST

    $_POST

  • $_SERVER

    $_SERVER

  • $_FILES

    $_FILES

PHP数据类型 (PHP Data Types)

Variables can store data of different types such as:

变量可以存储不同类型的数据,例如:

  • String ("Hello")

    字符串(“ Hello”)
  • Integer (5)

    整数(5)
  • Float (also called double) (1.0)

    浮点(也称为double)(1.0)
  • Boolean ( 1 or 0 )

    布尔值(1或0)
  • Array ( array("I", "am", "an", "array") )

    Array(array(“ I”,“ am”,“ an”,“ array”)))
  • Object

    目的
  • NULL

    空值
  • Resource

    资源资源

弦乐 (Strings)

A string is a sequence of characters. It can be any text inside quotes (single or double):

字符串是字符序列。 它可以是引号内的任何文本(单引号或双引号):

$x = "Hello!";
$y = 'Hello!';

整数 (Integers)

An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.

整数数据类型是-2,147,483,648和2,147,483,647之间的非十进制数。

Rules for integers:

整数规则:

  • Integers must have at least one digit

    整数必须至少有一位数字
  • Integers must not have a decimal point

    整数不能带小数点
  • Integers can be either positive or negative

    整数可以是正数或负数

$x = 5;

$x = 5;

浮点数 (Floats)

A float, or floating point number, is a number with a decimal point.

浮点数或浮点数是带小数点的数字。

$x = 5.01;

$x = 5.01;

布尔值 (Booleans)

A Boolean represents two possible states: TRUE or FALSE. Booleans are often used in conditional testing.

布尔值表示两种可能的状态:TRUE或FALSE。 在条件测试中经常使用布尔值。

$x = true;
$y = false;

数组 (Arrays)

An array stores multiple values in one single variable.

数组将多个值存储在一个变量中。

$colors = array("Magenta", "Yellow", "Cyan");

$colors = array("Magenta", "Yellow", "Cyan");

空值 (NULL)

Null is a special data type that can only have the value null. Variables can be declared with no value or emptied by setting the value to null. Also, if a variable is created without being assigned a value, it is automatically assigned null.

Null是一种特殊的数据类型,只能具有值null 。 变量可以不带任何值声明,也可以通过将其设置为null来清空。 同样,如果创建变量时未分配值,则会自动将其分配为null

<?php
// Assign the value "Hello!" to greeting
$greeting = "Hello!";

// Empty the value greeting by setting it to null
$greeting = null;
?>

类和对象 (Classes and Objects)

A class is a data structure useful for modeling things in the real world, and can contain properties and methods. Objects are instances a class, and are a convenient way to package values and functions specific to a class.

类是用于在现实世界中建模事物的数据结构,并且可以包含属性和方法。 对象是类的实例,并且是打包特定于类的值和函数的便捷方法。

<?php
class Car {
    function Car() {
        $this->model = "Tesla";
    }
}

// create an object
$Lightning = new Car();

// show object properties
echo $Lightning->model;
?>

PHP资源 (PHP Resource)

A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. You can use getresourcetype() function to see resource type.

资源是一个特殊变量,包含对外部资源的引用。 资源由特殊功能创建和使用。 您可以使用get resource type()函数查看资源类型。

<?php
// prints: mysql link
$c = mysql_connect();
echo get_resource_type($c) . "\n";

// prints: stream
$fp = fopen("foo", "w");
echo get_resource_type($fp) . "\n";

// prints: domxml document
$doc = new_xmldoc("1.0");
echo get_resource_type($doc->doc) . "\n";

弦乐 (Strings)

A string is series of characters. These can be used to store any textual information in your application.

字符串是一系列字符。 这些可用于在您的应用程序中存储任何文本信息。

There are a number of different ways to create strings in PHP.

有很多不同的方法可以在PHP中创建字符串。

单引号 (Single Quotes)

Simple strings can be created using single quotes.

可以使用单引号创建简单的字符串。

$name = 'Joe';

To include a single quote in the string, use a backslash to escape it.

要在字符串中包含单引号,请使用反斜杠将其转义。

$last_name = 'O\'Brian';

双引号 (Double Quotes)

You can also create strings using double quotes.

您还可以使用双引号创建字符串。

$name = "Joe";

To include a double quote, use a backslash to escape it.

要包含双引号,请使用反斜杠将其转义。

$quote = "Mary said, \"I want some toast,\" and then ran away.";

Double quoted strings also allow escape sequences. These are special codes that put characters in your string that represent typically invisible characters. Examples include newlines \n, tabs \t, and actual backslashes \\.

双引号字符串也允许转义序列。 这些是特殊的代码,用于在字符串中放置通常表示不可见字符的字符。 示例包括换行符\n ,制表符\t和实际反斜杠\\

You can also embed PHP variables in double quoted strings to have their values added to the string.

您还可以将PHP变量嵌入双引号字符串中,以将其值添加到字符串中。

$name = 'Joe';
$greeting = "Hello $name"; // now contains the string "Hello Joe"

字符串函数 (String Functions)

查找字符串的长度 (Find the length of a string)

The strlen() function returns the length of a string.

strlen()函数返回字符串的长度。

<?php
echo strlen("Developer News"); // outputs 14
?>

Find the number of words in a stringThe strwordcount() function returns the number of words in a string:

查找字符串中str word count()函数返回字符串中str word count()

<?php
echo str_word_count("Developer News"); // outputs 2
?>
反转字符串 (Reverse a String)

The strrev() function reverses a string:

strrev()函数可反转字符串:

<?php
echo strrev("Developer News"); // outputs sweN repoleveD
?>
在字符串中搜索文本 (Search for text within a string)

The strpos() function searches for text in a string:

strpos()函数搜索字符串中的文本:

<?php
echo strpos("Developer News", "News"); // outputs 10
?>
替换字符串中的文本 (Replace Text Within a String)

The str_replace() function replaces text in a string:

str_replace()函数替换字符串中的文本:

<?php
echo str_replace("freeCodeCamp", "Developer", "freeCodeCamp News"); // outputs Developer News
?>

常数 (Constants)

Constants are a type of variable in PHP. The define() function to set a constant takes three arguments - the key name, the key's value, and a Boolean (true or false) which determines whether the key's name is case-insensitive (false by default). A constant's value cannot be altered once it is set. It is used for values which rarely change (for example a database password OR API key).

常量是PHP中的一种变量。 用于设置常量的define()函数采用三个参数-密钥名称,密钥值和一个布尔值(true或false),该布尔值确定密钥名称是否不区分大小写(默认为false)。 常数的值一旦设置就无法更改。 它用于很少更改的值(例如数据库密码或API密钥)。

范围 (Scope)

It is important to know that unlike variables, constants ALWAYS have a global scope and can be accessed from any function in the script.

重要的是要知道,与变量不同,常量始终具有全局范围,并且可以从脚本中的任何函数进行访问。

<?php
define("freeCodeCamp", "Learn to code and help nonprofits", false);
echo freeCodeCamp;
>?

// Output: Learn to code and help nonprofits

Also, when you are creating classes, you can declare your own constants.

同样,在创建类时,可以声明自己的常量。

class Human {
  const TYPE_MALE = 'm';
  const TYPE_FEMALE = 'f';
  const TYPE_UNKNOWN = 'u'; // When user didn't select his gender
  
  .............
}

Note: If you want to use those constants inside the Human class, you can refer them as self::CONSTANT_NAME. If you want to use them outside the class, you need to refer them as Human::CONSTANT_NAME.

注意:如果要在Human类中使用这些常量,可以将其称为self::CONSTANT_NAME 。 如果要在课程之外使用它们,则需要将它们引用为Human::CONSTANT_NAME

经营者 (Operators)

PHP contains all the normal operators one would expect to find in a programming language.

PHP包含人们期望用编程语言找到的所有普通运算符。

A single “=” is used as the assignment operator and a double “==” or triple “===” is used for comparison.

单个“ =”用作赋值运算符,而两个“ ==”或三重“ ===”用于比较。

The usual “<” and “>” can also be used for comparison and “+=” can be used to add a value and assign it at the same time.

通常的“ <”和“>”也可用于比较,“ + =”可用于添加值并同时分配值。

Most notable is the use of the “.” to concatenate strings and “.=” to append one string to the end of another.

最值得注意的是使用“。” 连接字符串,使用“。=”将一个字符串附加到另一字符串的末尾。

New to PHP 7.0.X is the Spaceship operator (<=>). The spaceship operator returns -1, 0 or 1 when $a is less than, equal to, or greater than $b.

PHP 7.0.X的新增功能是Spaceship运算符(<=>)。 当$ a小于,等于或大于$ b时,太空船运算符将返回-1、0或1。

<?php

echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

If / Else / Elseif语句 (If / Else / Elseif Statements)

If / Else is a conditional statement where depending on the truthiness of a condition, different actions will be performed.

如果/ Else是一个条件语句,根据条件的真实性,将执行不同的操作。

Note: The {} brackets are only needed if the condition has more than one action statement; however, it is best practice to include them regardless.

注意:仅当条件具有多个动作语句时,才需要使用{}括号; 但是,最佳做法是无论如何都将它们包括在内。

如果声明 (If Statement)

<?php

  if (condition) {
    statement1;
    statement2;
  }

Note: You can nest as many statements in an "if" block as you'd like; you are not limited to the amount in the examples.

注意:您可以根据需要在“ if”块中嵌套尽可能多的语句; 您不限于示例中的金额。

如果/否则声明 (If/Else Statement)

<?php

  if (condition) {
    statement1;
    statement2;
  } else {
    statement3;
    statement4;
  }

Note: The else statement is optional.

注意: else语句是可选的。

If / Elseif / Else语句 (If/Elseif/Else Statement)

<?php

  if (condition1) {
    statement1;
    statement2;
  } elseif (condition2) {
    statement3;
    statement4;
  } else {
    statement5;
  }

Note: elseif should always be written as one word.

注意: elseif应该始终写成一个单词。

嵌套If / Else语句 (Nested If/Else Statement)

<?php

  if (condition1) {
      if (condition2) {
        statement1;
        statement2;
      } else {
        statement3;
        statement4;
      }
  } else {
      if (condition3) {
        statement5;
        statement6;
      } else {
        statement7;
        statement8;
      }
  }

多种条件 (Multiple Conditions)

Multiple conditions can be used at once with the "or" (||), "xor", and "and" (&&) logical operators.

多个条件可以与“或”(||),“异或”和“与”(&&)逻辑运算符一起使用。

For instance:

例如:

<?php

  if (condition1 && condition2) {
    echo 'Both conditions are true!';
  } elseif (condition 1 || condition2) {
    echo 'One condition is true!';
  } else (condition1 xor condition2) {
    echo 'One condition is true, and one condition is false!';
  }

Note: It's a good practice to wrap individual conditions in parens when you have more than one (it can improve readability).

注意:如果有多个条件,则将单个条件包装在括号中是一个好习惯(这可以提高可读性)。

替代If / Else语法 (Alternative If/Else Syntax)

There is also an alternative syntax for control structures

控制结构还有另一种语法

if (condition1):
    statement1;
  else:
    statement5;
  endif;

三元运算符 (Ternary Operators)

Ternary operators are basically single line if / else statements.

三元运算符基本上是单行if / else语句。

Suppose you need to display "Hello (user name)" if a user is logged in, and "Hello guest" if they're not logged in.

假设如果用户已登录,则需要显示“ Hello(用户名)”,如果用户未登录,则需要显示“ Hello guest”。

If / Else statement:

如果/其他声明

if($user == !NULL {
  $message = 'Hello '. $user; 
} else {
  $message = 'Hello guest';
}

Ternary operator:

三元运算符

$message = 'Hello '.($user == !NULL ? $user : 'Guest');

开关 (Switch)

In PHP, the Switch statement is very similar to the JavaScript Switch statement (See the JavaScript Switch Guide to compare and contrast). It allows rapid case testing with a lot of different possible conditions, the code is also more readable.

在PHP中, Switch语句与JavaScript Switch语句非常相似(请参阅JavaScript Switch Guide进行比较和对比)。 它允许在许多不同的可能条件下进行快速案例测试,代码也更具可读性。

<?php
	// Switch Statement Example
	switch ($i) {
    	case "free":
    	    echo "i is free";
    	    break;
    	case "code":
    	    echo "i is code";
    	    break;
    	case "camp":
    	    echo "i is camp";
    	    break;
    	default:
    	    echo "i is freecodecamp";
            break;
	}

打破 (Break)

The break; statement exits the switch and goes on to run the rest of the application's code. If you do not use the break; statement you may end up running multiple cases and statements, sometimes this may be desired in which case you should not include the break; statement.

break; 语句退出开关,然后继续运行应用程序的其余代码。 如果不使用break; 声明您可能最终会运行多个案例和声明,有时可能需要这样做,在这种情况下,您不应该包含break; 声明。

An example of this behavior can be seen below:

可以在下面看到此行为的示例:

<?php
    $j = 0;

    switch ($i) {
        case '2':
            $j++;
        case '1':
            $j++;
            break;
        default:
            break;
    }

If $i = 1, the value of $j would be:

如果$ i = 1,则$ j的值为:

1

If $i = 2, the value of $j would be:

如果$ i = 2,则$ j的值为:

2

While break can be omitted without causing fall-through in some instances (see below), it is generally best practice to include it for legibility and safety (see below):

尽管在某些情况下可以忽略中断而不会导致失败(请参阅下文),但通常最好的做法是将其包括在内以提高可读性和安全性(请参阅下文):

<?php
    switch ($i) {
        case '1':
            return 1;
        case '2':
            return 2;
        default:
            break;
     }
<?php
    switch ($i) {
        case '1':
            return 1;
            break;
        case '2':
            return 2;
            break;
        default:
            break;
     }

(Example)

<?php
//initialize with a random integer within range
$diceNumber = mt_rand(1, 6);

//initialize
$numText = "";

//calling switch statement
  switch($diceNumber) 
  {
  case 1:
    $numText = "One";
    break;
  case 2:
    $numText = "Two";
    break;
  case 3:
  case 4:
    // case 3 and 4 will go to this line
    $numText = "Three or Four";
    break;
  case 5:
    $numText = "Five";
    echo $numText;
    // break; //without specify break or return it will continue execute to next case.
  case 6:
    $numText = "Six";
    echo $numText;
    break;
  default:
    $numText = "unknown";
  }
  
  //display result
  echo 'Dice show number '.$numText.'.';

?>

输出量 (Output)

if case is 1
> Dice show number One.

if case is 2
> Dice show number Two.

if case is 3
> Dice show number Three or Four.

if case is 4
> Dice show number Three or Four.

if case is 5
> FiveSixDice show number Six.

if case is 6
> SixDice show number Six.

if none of the above
> Dice show number unknown.

循环 (Loops)

When you need to repeat a task multiple times, you can use a loop instead of adding the same code over and over again.

当需要多次重复执行任务时,可以使用循环,而不必一次又一次地添加相同的代码。

Using a break within the loop can stop the loop execution.

在循环中使用break可以停止循环执行。

对于循环 (For loop)

Loop through a block of code a specific number of times.

遍历代码块特定次数。

<?php
for($index = 0; $index < 5; $index ++)
{
    echo "Current loop counter ".$index.".\n";
}
?>

/*
Output:

Current loop counter 0.
Current loop counter 1.
Current loop counter 2.
Current loop counter 3.
Current loop counter 4.
*/

While循环 (While loop)

Loop through a block of code if a condition is true.

如果条件为真,则循环遍历代码块。

<?php
$index = 10;
while ($index >= 0)
{
    echo "The index is ".$index.".\n";
    $index--;
}
?>

/*
Output:

The index is 10.
The index is 9.
The index is 8.
The index is 7.
The index is 6.
The index is 5.
The index is 4.
The index is 3.
The index is 2.
The index is 1.
The index is 0.
*/

当...循环时 (Do...While loop)

Loop through a block of code once and continue to loop if the condition is true.

循环遍历代码块一次,如果条件为真,则继续循环。

<?php
$index = 3;
do
{
    // execute this at least 1 time
    echo "Index: ".$index.".\n"; 
    $index --;
}
while ($index > 0);
?>

/*
Output:

Index: 3.
Index: 2.
Index: 1.
*/

Foreach循环 (Foreach loop)

Loop through a block of code for each value within an array.

为数组中的每个值循环遍历代码块。

功能 (Functions)

A function is a block of statements that can be used repeatedly in a program.

函数是可以在程序中重复使用的语句块。

简单功能+通话 (Simple Function + Call)

function say_hello() {
  return "Hello!";
}

echo say_hello();

简单功能+参数+调用 (Simple Function + Parameter + Call)

function say_hello($friend) {
  return "Hello " . $friend . "!";
}

echo say_hello('Tommy');

strtoupper-使所有字符变得越来越大! (strtoupper - Makes all Chars BIGGER AND BIGGER!)

function makeItBIG($a_lot_of_names) {
  foreach($a_lot_of_names as $the_simpsons) {
    $BIG[] = strtoupper($the_simpsons);
  }
  return $BIG;
}

$a_lot_of_names = ['Homer', 'Marge', 'Bart', 'Maggy', 'Lisa'];
var_dump(makeItBIG($a_lot_of_names));

数组 (Arrays)

Arrays are like regular variables, but hold multiple values in an ordered list. This can be useful if you have multiple values that are all related to each other, like a list of student names or a list of capital cities.

数组就像常规变量一样,但是在有序列表中包含多个值。 如果您有多个相互关联的值,例如学生姓名列表或省会城市列表,则此功能很有用。

数组类型 (Types Of Arrays)

In PHP, there are two types of arrays: Indexed arrays and Associative arrays. Each has their own use and we'll look at how to create these arrays.

在PHP中,有两种类型的数组:索引数组和关联数组。 每个都有自己的用途,我们将研究如何创建这些数组。

索引数组 (Indexed Array)

An indexed array is a list of ordered values. Each of these values in the array is assigned an index number. Indexes for arrays always start at 0 for the first value and then increase by one from there.

索引数组是有序值的列表。 数组中的每个值都分配有一个索引号。 数组的索引始终从第一个值的0开始,然后从那里开始加一。

<?php
$shopping_list = array("eggs", "milk", "cheese");
?>

$shopping_list[0] would return "eggs", $shopping_list[1] would return "milk", and $shopping_list[2] would return "cheese".

$shopping_list[0]将返回"eggs"$shopping_list[1]将返回"milk" ,而$shopping_list[2]将返回"cheese"

关联数组 (Associative Array)

An associative array is a list of values that are accessed via a key instead of index numbers. The key can be any value but it must be unique to the array.

关联数组是通过键而不是索引号访问的值的列表。 键可以是任何值,但对于数组必须是唯一的。

<?php
$student_scores = array("Joe" => 83, "Frank" => "93", "Benji" => "90");
?>

$student_scores['Joe'] would return 83, $student_scores['Frank'] would return 93, $student_scores['Benji'] would return 90.

$student_scores['Joe']将返回83$student_scores['Frank']将返回93$student_scores['Benji']将返回90

多维数组 (Multidimensional Array)

A multidimensional array is an array that contains other arrays. This lets you create complex data structures that can model a very complex group of data.

多维数组是包含其他数组的数组。 这使您可以创建复杂的数据结构,从而可以对非常复杂的数据组进行建模。

<?php
$students = 
  array(
    array("first_name" => "Joe", "score" => 83, "last_name" => "Smith"),
    array("first_name" => "Frank", "score" => 92, "last_name" => "Barbson"),
    array("first_name" => "Benji", "score" => 90, "last_name" => "Warner")   
  );
?>

Now you can get the first student's first_name with:

现在,您可以通过以下方式获取第一个学生的first_name

$students[0]['first_name']

获取数组的长度-count()函数 (Get The Length of an Array - The count() Function)

The count() function is used to return the length (the number of elements) of an array:

count()函数用于返回数组的长度(元素数):

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>

排序数组 (Sorting Arrays)

PHP offers several functions to sort arrays. This page describes the different functions and includes examples.

PHP提供了一些对数组进行排序的功能。 此页面描述了不同的功能并包括示例。

分类() (sort())

The sort() function sorts the values of an array in ascending alphabetical/numerical order (E.g. A, B, C, D, E... 5, 4, 3, 2, 1...)

sort()函数以字母/数字升序对数组的值进行排序(例如A,B,C,D,E ... 5、4、3、2、1 ...)

<?php
$freecodecamp = array("free", "code", "camp");
sort($freecodecamp);
print_r($freecodecamp);
?>

Output:

输出

Array
(
    [0] => camp
    [1] => code
    [2] => free
)

rsort() (rsort())

The rsort() functions sort the values of an array in descending alphabetical/numerical order (E.g. Z, Y, X, W, V... 5, 4, 3, 2, 1...)

rsort()函数以字母/数字降序对数组的值进行排序(例如Z,Y,X,W,V ... rsort() ...)

<?php
$freecodecamp = array("free", "code", "camp");
rsort($freecodecamp);
print_r($freecodecamp);
?>

Output:

输出:

Array
(
    [0] => free
    [1] => code
    [2] => camp
)

asort() (asort())

The asort() function sorts an associative array, by it's values, in ascending alphabetical/numerical order (E.g. A, B, C, D, E... 5, 4, 3, 2, 1...)

asort()函数按其值以字母/数字升序对关联数组进行排序(例如A,B,C,D,E ... 5、4、3、2、1 ...)

<?php
$freecodecamp = array("zero"=>"free", "one"=>"code", "two"=>"camp");
asort($freecodecamp);
print_r($freecodecamp);
?>

Output:

输出:

Array
(
    [two] => camp
    [one] => code
    [zero] => free
)

ksort() (ksort())

The ksort() function sorts an associative array, by it's keys, in ascending alphabetical/numerical order (E.g. A, B, C, D, E... 5, 4, 3, 2, 1...)

ksort()函数按键对关联数组按字母/数字升序排序(例如A,B,C,D,E ... 5、4、3、2、1 ...)

<?php
$freecodecamp = array("zero"=>"free", "one"=>"code", "two"=>"camp");
ksort($freecodecamp);
print_r($freecodecamp);
?>

Output:

输出:

Array
(
    [one] => code
    [two] => camp
    [zero] => free
)

arsort() (arsort())

The arsort() function sorts an associative array, by it's values, in descending alphabetical/numerical order (E.g. Z, Y, X, W, V... 5, 4, 3, 2, 1...)

arsort()函数按其值的字母/数字降序对关联数组进行排序(例如Z,Y,X,W,V ... 5、4、3、2、1 ...)

<?php
$freecodecamp = array("zero"=>"free", "one"=>"code", "two"=>"camp");
arsort($freecodecamp);
print_r($freecodecamp);
?>

Output:

输出:

Array
(
    [zero] => free
    [one] => code
    [two] => camp
)

krsort() (krsort())

The krsort() function sorts an associative array, by it's keys in descending alphabetical/numerical order (E.g. Z, Y, X, W, V... 5, 4, 3, 2, 1...)

krsort()函数通过其键以字母/数字降序对关联数组进行排序(例如Z,Y,X,W,V ... krsort() ...)

<?php
$freecodecamp = array("zero"=>"free", "one"=>"code", "two"=>"camp");
krsort($freecodecamp);
print_r($freecodecamp);
?>

Output:

输出:

Array
(
    [zero] => free
    [two] => camp
    [one] => code
)

形式 (Forms)

Forms are a way for users to enter data or select data from the webpage. Forms can store data as well as allow the information to be retrieved for later use.

表单是用户输入数据或从网页中选择数据的一种方式。 表单可以存储数据,也可以检索信息以供以后使用。

To make a form to work in languages like PHP you need some basic attributes in html. In most cases PHP uses 'post' and 'get' super global variables to get the data from form.

为了使表单能够在PHP之类的语言中工作,您需要html中的一些基本属性。 在大多数情况下,PHP使用'post'和'get'超级全局变量从表单获取数据。

<html>
<body>
  <form method="get" action="target_proccessor.php">
      <input type="search" name="search" /><br />
      <input type="submit" name="submit" value="Search" /><br />
  </form>
<body>
</html>

The 'method' attribute here tell the form the way to send the form data. Then the 'action' attribute tell where to send form data to process. Now the 'name' attribute is very important and it should be unique because in PHP the value of the name work as the identity of that input field.

这里的“方法”属性告诉表单发送表单数据的方式。 然后,“ action”属性告诉将表单数据发送到哪里进行处理。 现在,“名称”属性非常重要,它应该是唯一的,因为在PHP中,名称的值用作该输入字段的标识。

检查所需的输入 (Checking Required Inputs)

PHP has a few functions to check if the required inputs have been met. Those functions are isset, empty, and is_numeric.

PHP具有一些功能来检查是否已满足所需的输入。 这些函数分别是issetemptyis_numeric

检查表格以确保其设置 (Checking form to make sure its set)

The isset checks to see if the field has been set and isn't null. Example:

isset检查该字段是否已设置并且不为null。 例:

$firstName = $_GET['firstName']

if(isset($firstName)){
  echo "firstName field is set". "<br>";
}
else{
  echo "The field is not set."."<br>";
}

处理表格输入 (Handling Form Input)

One can get form inputs with global variables $POST and $GET.

可以获取带有全局变量$ POST和$ GET的表单输入。

$_POST["firstname"] or $_GET['lastname']

翻译自: https://www.freecodecamp.org/news/the-best-php-examples/

php 入门示例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值