Introduction to PHP Basic syntax

Source: Internet
Author: User
Tags arithmetic operators float double php introduction scalar script tag type null value of pi
This article mainly introduces the basic syntax of PHP introduction, has a certain reference value, now share to everyone, the need for friends can refer to

Knowledge Points:

    1. Marker, Comment

    2. Variable

    3. Constant

    4. Data type

    5. Operator

    6. Process Control

Marker, Comment

4 Marker Symbols:

1. Default form: <?php PHP statement ?>

If <?php ...? After > No HTML code, the?> tag can be omitted

2. Short label form: <? PHP Statement ?>

The default is off, you need to turn on the configuration item "php.ini": short_open_tag=on

3. Script tag form: <script language= "php" > PHP statement </script>

4. asp form: <% PHP statement%>

The default is off, you need to turn on the configuration item "php.ini":asp_tags =on

Uppercase and lowercase

  Variable: Case sensitive

Constants: Case-sensitive, can be configured in the php.ini file to be case insensitive

Other case insensitive: such as function name, System keyword ...

Comments

Single-line Comment://comment content or #注释内容

Multiline Comment:/* Comment content */

Variable

Concept:

An "identifier" representing a certain amount of storage space and the data therein

The assignment defines the variable at the same time, $v 1 = 1; Icon:

Naming rules

Start with a letter or underscore followed by any number (with 0) letters, numbers, and underscores

Common naming:

       Camel nomenclature : The first word in lowercase, followed by the first letter of each word capitalized. such as: $myName
       Pascal Nomenclature : Capitalize each word in the first letter. such as: $MyName
       Underline Segmentation : Each word is lowercase and is separated by an underscore. such as: $my _name

  Basic operations

Values such as $v = 12.3; $m =round ($v)

Assign values such as $v = 12.3;

Judge Isset () to determine if the variable exists, or if the variable has a data value!

Delete unset (): Break the reference relationship between the variable name and the value of the variable's original data

Transfer value Form

    value passing : values are equal and independent of each other. such as $v 1 = 1; $v 2 = $v 1; Icon:

Both the value of the variable $v1 is copied, and then the other variable v2 is assigned

    reference passing: Essentially, 2 variables point to the same data space. such as $m 1 = 1; $m 2 = & M1; Icon:

$M1 a "referential relationship" between a variable and its data value, copying a copy and giving the variable $m2

  Variable variable

The variable form of "$" appears consecutively. such as: $v = "a"; $a = 10; Then $ $v = 10.

1 <?php  2      //variable variable  3     $v 1 = 123;   4     $v 2 = 221;  5     $v 3 = 3;  6     $v 4 = 9;  7     $v 5 =;  8     $v 6 =;  9     //variable and one     $sum = 0;//for storage and for     ($i = 1; $i <= 6; $i + +) {         $v = "V". $i;         $sum + = $ $v;     }16     echo $sum;?>

Click to view-variable variable usage

Pre-defined variables

Hyper Global Array, with Hyper global scope, system definition and maintenance. Mainly $_post, $_get,$_request,$_server, $GLOBALS, $_cookie,$_session ....

    $_post All data submitted by the form in post (method= "POST") will receive data such as: $name = $_post[' name '];

      Form submission Data note: For radio and checkbox data is not received, and other non-filled will receive

    $_get All data submitted by the GET method to receive data such as: $name = $_get[' name ');

There are 5 ways to implement get commit data

Form 1:form form Get submit

such as <form method= "get" action= "index.php" > ... </form>

Form 2:A Label Submission

such as <a href= "index.php?name=young&gender=male&age=18" > Home </a>

Form 3:js Jump Submit 1

such as:<script> location.href= "index.php?name=young&gender=male&age=18"; </script>

Form 4:js Jump Submit

such as:<script>location.assign= "index.php?name=young&gender=male&age=18"; </script>

Form 5:php Jump Submit

such as: Header ("location: index.php?name=young&gender=male&age=18");

    $_request is a "collection" of $_get variables and $_post variable data: That is, it stores both of these data. Receive data such as: $name = $_request[' name '];

The submission form can have both get and post data.

such as <form method= "POST" action= "Index.php?name=young&gender=male" >.....</form>

When receiving data, if the POST is the same as the GET data item name, such as $_post[' name ']= ' young ', $_get[' name ']= ' admin '.

If received using the $_request method, the post data overwrites the get data.

Can be set by configuration item "PHP.ini": request_order= "GP" G for Get p for post the latter to overwrite the former

    $_server represents some information or server-side information on the browser side during a Web page visit

Common options:

$_server["REMOTE_ADDR"] Visitor IP Address

$_server["SERVER_ADDR"] Server IP Address

$_server["SERVER_NAME"] Server name is set in both the site configuration servername such as: www.test.com

$_server[' Document_root '] site physical address. DocumentRoot set in both site configurations such as: d:/www

$_server["php_self"] current page address, not including domain names such as/index.php

$_server["Script_filename"] the physical path of the current Web page, such as d:/demo/index.php

$_server["Query_string"] gets all the get data in the current page address (both , but only a whole string, such as: Id=2&name=young

    $GLOBALS : Stores all global variables. Can be used to get the value of the specified global variable when the global variable is not available at the local scope

Isset () and Empty ()

Isset (variable): Determines whether the variable exists , or whether the variable is empty (null), if present, returns true, otherwise false

Empty (variable): Determines whether the "content" of the variable is empty, the content is empty, returns true, otherwise false

Empty case: 0 0.0 "" "0" false null array () empty arrays

Constant

Concept

Meaning: Is the "identifier" in which the data stored is not and should not be changed

Defined

Mode 1: define (' Constant name ', value) , such as: Define (' PI ', 3.14);

Mode 2: Const constant NAME = value; for example: const host= ' localhost ';

Note: The const syntax can only be used in the "top-level code" position , not in the position of curly braces

Take value

Form 1: Direct use of constant names such as: Echo PI;

Form 2: Use function constant (' constant name ') such as Echo constant (' PI ');

The difference from a variable

Different form of definition
Use different form: constant without $ symbol
Varying degrees of variability, constant values cannot be changed, and constants cannot be destroyed
Different scopes: Constants have a super global scope (functions can be used directly inside and outside the function)
Available types are different: constants can only store scalar types (integers, floating-point numbers, strings, Boolean values)

Determine if there is

Defined ("constant name") exists return true does not exist return false

With undefined constants, there is a notice warning that the undefined constant name will be used as its value

Pre-defined constants

Common: "Reference to PHP manual Appendix" reserved word list "predefined constants"

M_PI: Is the constant value of pi
Php_os: The operating system where PHP is running
Php_version: Is the version number of PHP
The largest integer value in the php_int_max:php

Magic Constants

__FILE__ the physical path of the Web page that represents the current Web page file
__DIR__ represents the directory where the current Web page file resides
__LINE__ represents the line number where the constant name is currently located

Data type

8 Types of data

Base data type (scalar type)

Integral type: int Interger
Float type: Float double such as: $v 1 = 123.456E2; The meaning is: 123.456 times 10 of the 2-time Square

Do not use floating-point numbers for size comparisons, and if you want to compare floating-point numbers, convert them to integers before comparing them. If the required precision is 3 decimal places, multiply by 1000 and then compare after rounding

When the result of an integer operation is outside the range of an integer, it is automatically converted to a floating-point number
String Type: String
Boolean type: BOOL Boolean

Composite type:

Arrays: Array

Objects: Object

Special types:

Empty type Null in this type, there is only one data, that is null
Resource type Resource

Integer type binary conversions

Integer type

0b1010 (binary), 0123 (octal), 123 (decimal), 0x123 (hex)

Bin: Binary Oct: octal dec: decimal hex:16 binary

Hand-made conversion

      10 binary conversion to 2 binary: Except for 2 the remainder is inverted to write out all remainders

Divide a 10 binary number by 2 to get the quotient and remainder, and if the quotient is also greater than or equal to 2, continue to divide by 2, continue to get quotient and remainder, and so on,

Until the quotient is 0, and then the previous remainder is written in reverse order to the corresponding 2 binary digits

      10 binary conversion to 8 binary: Except for 8 the remainder is inverted to write out all remainders

      10 binary conversion to 16 binary: Except for 16 the remainder is inverted to write out all remainders

      8 binary to 10 : Multiplies the number of digits on each bit of the 8-digit number by the weight on its corresponding bit, then adds the result

      16 binary to 10 : Multiplies the number of digits on each bit of the 16-digit number by the weight on its corresponding bit, then adds the result

      2 binary to 10 : Multiplies the number of digits on each bit of the 2-digit number by the weight on its corresponding bit, then adds the result

      Decimal Binary Practice : Multiply by 2 and sequentially take the integral number of parts

Decimal conversion to other binary

      Decbin (a 10 binary number): The result returns a string of 2 binary digits of the number
      decoct ( a 10 binary number): The result returns a string of 8 binary digits of the number
      Dechex (a 10 binary number): The result returns a string of 16 binary digits of the number

Other binary conversions to decimal

      Bindec (a 2-digit string): The result returns a number in the form of a 10 binary number corresponding to the 2 binary string
      Octdec (A 8-digit string): The result returns a number in the form of a 10 binary number corresponding to the 8 binary string
      Hexdec (A 16-digit string): The result returns a number in the form of a 10 binary number corresponding to the 16 binary string

Get data type

GetType ($ variable): Returns the name of the type (string)
Var_dump ($ variable): Outputs the variable's type, data content, (and length)

  4 Types of strings

Form 1: single quote $str = ' Hello '; the escaped character that can be recognized is: \ \ \ '
Form 2: double quotation mark $str = "Hello"; the escaped character that can be recognized is: \ \ \ \ n (newline character) \ r (carriage return) \ t (tab character)
Form 3: double quote delimiter Heredoc: The escaped character that can be recognized is: \ \ \ \ \ \ \$

1  $str = <<< "LAB" 2         This is a "test"!! v1= $v 1;3 lab;4//NOTE: The end line can only be identifiers and semicolons

Form 4: single quote delimiter Nowdoc:

1 $str = <<< ' lab ' 2 This is         a test!3 lab;

  Data type conversions

In any operation, if a certain type of data is required and the given data is not of that type, an automatic conversion usually occurs

    Automatic conversion : determined by the "operator" or similar operator statement

Arithmetic operations, calculated only for numeric values

Conversion rules for numbers in strings: identify only the preceding digits of the string, such as 1+ "3a5b" =4

    cast :

Form: ( target type) data such as (int) $a;

The target types are usually: Int,float,string,bool,array,object

The conversion does not change the variable itself, but changes the variable itself, using Settype ($var, $value);

common Type-related system functions

    Var_dump () Print the full information of the variable
GetType ($var) Gets the name of the variable's type (string)
SetType ($var, $type) The type of the cast variable
isset () variable is set
Empty () the value of the empty () variable
unset () Delete variable
is_xx Series functions: Judging whether it is a type
Is_int ($x) to determine if it is an integer type
is_float () Determine if it is a floating-point type
is_string () to determine if it is a string type
Is_bool () to determine if it is a Boolean type
Is_array () to determine if an array is
Is_object () Determine if it is an object
Is_null () to determine if it is null
Is_numeric () is a number
Is_scalar () is a scalar type (int,float,bool,string)

Operator

Arithmetic operators

Symbol: +-*/% + +--

Used to operate on numbers, which are automatically converted to numbers if they are non-numeric on either side of the symbol.

     The remainder (%) is calculated by first taking the whole in the remainder . such as 11.3%3 equivalent to 11%3.

+ +,--only for numbers or letters. The string can also be self-increment or decrement.

such as: $val = "abc"; $val + +; Echo $val; $val = "Abd";

$va = "ABC9"; $va + +; Echo $va; $va = "abd0";

"Former self-increment" first to the variable to do other operations, "after self-increment" first to do other operations on the self-added variable plus 1, self-reduction is similar.

Comparison operators

Symbol: > < >= <= = = = = = = = = =!==

Do not compare the size of floating-point numbers.

Comparison rules between scalars:

In the comparison data, there is a Boolean value that is automatically converted to a Boolean value to load for comparison.

Otherwise, if there is a numeric value in the data that is compared, it is automatically converted to a number for comparison.

Otherwise, if the data you are comparing is a "numeric string", it is automatically converted to a number and then compared

Otherwise, compare by string

logical operators

Symbol: && | | !

Logical operation note Short circuit phenomenon. If you want to judge more, simply put it in front.

String operators

Symbol: . .=

string connections, if both sides are not strings, are automatically converted to strings for connection

Assignment operators

= += -= *= /= %=

Conditional operator (trinocular)

Form: Data value 1? Result value 1: Result value 2;

If equivalent form: if (data value 1) {result value 1;} else {result value 2;}

If the result value 1 is omitted, it is itself. such as $res =100?:10; Result $res = 100;

Bit operation symbols

Symbol: & | ~ ^ << >>

Operation only for integer types

Bitwise XOR: The same is 0 different for 1. such as 1^1 = 0;

Comfort left shift operation <<: Right 0, left

Original code, anti-code, complement:

Positive inverse code: equal to its own, negative number of the anti-code: The sign bit is unchanged, the other bits take the reverse;

The complement of a positive number equals its own; the complement of a negative number: The sign bit is unchanged, and the other bits are reversed plus 1.

Array operators

Symbol: + = = = = = = =!==

For the array + sign: Array union, merge the right-hand array items to the left of the array, and get a new array. If there are duplicate keys, do not overwrite, keep the data on the left array.

such as: $arr = Array (1=>11,2=>22,3=>33); $narr = Array (3=>23,4=>24); $RESARR = $arr + $narr; Result: Array (1=>11,2=>22,3=>33,4=>24)

= =: Key name and value equality are true, order can be different.

Error suppression operators

Symbol: @

Can suppress error messages that may be generated. such as $conn =@ mysql_connect (...);

Operator precedence Reference manual: Language reference operator precedence of operator

Process Control

Draw flowchart

Start, end: to represent with an ellipse

Statement block: Rectangular shape

To judge: A quadrilateral with a pointing and pointing

Input and output: quadrilateral

Branching structure

If branch structure

1 if (condition 1) {2      branch 1; 3} else if (condition 2) {4 branch 2;5} .... else{6//else Branch 7}

Branching structure

Switch Branch structure

1  switch (expression) {2 case     value 1: Branch 1; 3         [break;]  You can omit 4 case     value 2: branch 2; 5         [break;]  6...         7     Default:default Branch; 8}9

Switch structure

Loop structure

1) for Loop

For ("Loop variable initialization"; "condition judgment for cyclic variables"; "Change of cyclic variable") {//Loop body statement ...}

2) while () loop

while ("condition judgment of the loop variable") {//Loop body statement ... "Change of cyclic variable"}

3) do. while () loop

do {//Loop body statement ... "Change of cyclic variable"}while ("condition Judgment of cyclic variable")

4) foreach () loop

5) Goto Statement

Cannot jump into a loop , cannot jump into a function , cannot jump out of a function, cannot jump out of a file

Identifier 2:    statement 1 ..... Goto identifier 1;   Meaning: Immediately jump to the location statement where identifier 1 is located ...    Identifier 1:    statement .... Goto  identifier 2;  Meaning: Jump immediately to the location where identifier 2 is located

Cyclic interrupts

1) Break: Completely terminate a loop and let the execution flow into the statement after the loop statement;
2) Continue: Stop the current ongoing cycle, and enter into the cycle of the "next" process to go;

3) interrupts the "more layers" loop, referring to the number of "external" loops of the code from the current interrupt statement (break or Continue) , which is the number of layers

Break positive integer n; such as: Break 1;
Continue positive integer n; such as: Continue 2;

For (...) {     //loop 1 for    (..) {   //loop 2 for         (..) {   //loop 3 break            2;    In this case, the Loop 2 is interrupted, in  fact, only the "2 layer"                    //on this break statement, the Loop 3 is its "1th layer", the Loop 2 is its "2nd layer", the Loop 1 is its "3rd layer"               }                continue 2;    In this case, the Loop 1 is interrupted, in  fact only the "2 layer"                   //To this continue statement, the Loop 2 is its "1th layer", the Loop 1 is its "2nd Layer"         }}

Process Control another way of writing

1 if (...):  ...     Endif;2 if (...):  ...  else: ...  Endif;3 if (...): ... elseif (...): ...   elseif (...): ...   else:   ......--------- Endif;4 switch (...): Case  ...  Case  ...  Endswitch;5 while (...): ...  Endwhile;6 for (...;    ... ; ...):  ...  ENDfor;

controlling script execution

1) Die (' string '); after outputting the string, stop PHP execution immediately!

2) Exit (' string '); after outputting the string, stop PHP execution immediately!

3) sleep ($num); Lets the program stop running for the specified number of seconds . After $num seconds have been waited, continue execution.

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.