Basic PHP syntax knowledge

Source: Internet
Author: User
: This article mainly introduces the basic syntax of PHP. if you are interested in the PHP Tutorial, you can refer to it. PHP (foreign name: Hypertext Preprocessor, Chinese name: "Hypertext Preprocessor") is a common open source scripting language. The syntax absorbs the features of C, Java, and Perl, which is easy to learn and widely used and mainly applies to the Web development field.

PHP's unique syntax is a mix of C, Java, Perl, and PHP's own syntax. It can execute dynamic web pages more quickly than CGI or Perl. Compared with other programming languages, PHP embeds programs into HTML (an application under the standard general Markup Language) documents for execution, the execution efficiency is much higher than the CGI that completely generates the HTML tag. PHP can also execute the compiled code to encrypt and optimize code execution, so that the code runs faster.

PHP constant:

Predefined constants:

PHP also defines a large number of predefined constants. you can use get_defined_constants () to view them. the commonly used predefined constants include:

PHP_ OS: PHP System.

PHP_VERSION: PHP version.

PHP_EOL: Line break (for cross-platform migration, it is very important). different values are used according to different operating systems. Different operating systems have different line breaks. Window: \ r \ n * nix: \ n MAC: \ r

PHP_INT_MAX: maximum integer value.

PHP_INT_SIZE: the number of bytes occupied by the integer.

PATH_SEPARATOR: delimiter between paths in environment variables.

DIRECTORY_SEPARATOR: directory separator. '\' And '/' under the window can be used, * nix can only use '/'.

Magic constant:

It is similar to a constant. it is really a constant. it is called a magic constant!

_ FILE __: complete FILE path and FILE name. Typical applications (Project code) such:

Define ('root _ path', str_replace ('7. php', '',__ FILE __));

Echo ROOT_PATH;

The result is equivalent to (_ DIR __, which is added in PHP5.3)

_ FUNCTION __: obtain the magic constant of the current FUNCTION name!

PHP hexadecimal conversion

In PHP, a series of Convert functions are provided:

Hex: hexadecimal; dec: decimal; oct: octal; bin: binary.

For example, decbin () converts a decimal number to a decimal number, and octhex () converts a decimal number to a hexadecimal number.

For an integer, once the value is too large, it does not overflow. Instead, it is converted to a float type.

Php does not support unsigned integers.

For example:

$ A = PHP_INT_MAX; // 2147483648.

$ B = $ a + 1;

Var_dump ($ B); // float

In php, float and double are actually the same. The floating point number has a 14-digit decimal number. The maximum value is related to the platform, usually 1.8e308. The comparison of floating point numbers is unreliable. When writing a program, do not try to obtain the business logic by comparing whether two floating point numbers are equal.

String definition method

There are four methods to define a string: double quotation marks, single quotation marks, heredoc (delimiter), nowdoc (delimiter)

Variables can be parsed using double quotation marks. variables cannot be parsed using single quotation marks. Single quotation marks can contain double quotation marks. double quotation marks can contain single quotation marks, but they cannot contain the quotation marks themselves.

Whether a variable can be parsed depends not on which variable is included, but on whether the defined string is single quotation marks or double quotation marks. if it is double quotation marks, the variable is parsed. if it is single quotation marks, it is not parsed.

In a string, if {$ is connected together, this variable in {} is parsed as a variable.

When a variable is considered NULL

1. The value is NULL.

2. not assigned

3. unset ()

One of the most common applications is to assign a NULL value to an object to destroy it.

Data type related functions

Var_dump (): Prints detailed information about a variable, including the type and value.

Gettype (): Get type.

Settype (): set the type.

Is series: is_array () is often used.

Isset (): check whether a variable exists (set ).

Empty (): check whether a variable is empty.

For isset (), if it has been declared (with a value), no matter what its value is, true is returned.

For empty (), it is equivalent to a boolean (variable) and then an inverse is obtained.

Convert to Boolean is considered FALSE

1. Boolean value FALSE itself

2. integer value 0 (0)

3. floating point value: 0.0 (0)

4. empty string and string "0" (note that "00" and "0.0" are considered TRUE)

5. empty array

6. Special type NULL (including unset variables)

All other values are considered TRUE (including objects and resources ).

PHP operation rules

The result of the division operation may be a floating point or an integer.

In the modulo operation, if there is a decimal point, the fractional part is removed.

In the modulo operation, the positive and negative results depend on the first number.

Original Code

Convert decimal to binary. Use the highest bit to represent the symbol bit, 0 to represent a positive number, and 1 to represent a negative number.

Reverse Code

For positive numbers, the reverse code is the same as the original code.

For negative numbers, the symbol bit remains unchanged, and the other bits are reversed.

Complement

For positive numbers, the complement code is the same as the original code.

For negative numbers, + 1 is added based on the anticode.

The symbols remain unchanged during transcoding, while the symbols are involved in the operation,

Shift operation

Right Shift: low overflow, the symbol bit remains unchanged, and the high position is supplemented with the symbol bit (equivalent to dividing by the n power of 2 and then taking the integer)

Left Shift: high overflow, symbol bit unchanged, low fill 0 (equivalent to multiply by the n power of 2)

Whether it is left or right shift, it only changes the size of the number without changing the symbol. Therefore, the symbol bit remains unchanged during the shift operation.

PHP operator number priority

And or and & |.

The usage is the same and the priority is different. &, | >=> And, or

Break: termination. when break is executed, the overall loop statement ends directly.

Continue: continue. the current loop body ends and the next loop body continues.

Include and require

Set the value of include_path

Use the set_include_path () function ().

Set_include_path ('d:/php/test'); then directly require 'File. php ',

Note: When Setting this parameter, the subsequent setting will overwrite the previous setting!

Obtain the value of the current include_path

Use the function: get_include_path () to obtain the current include_path value!

Use semicolons to connect directories.

Set_include_path ('d:/php/Test'. PATH_SEPARATOR.get_include_path ());

PHP has already compiled the code in the unit of the source file. if the current file has a syntax error, php will report an error. Code compilation is not performed.

Difference between require (require_once) and include (include_once)

When the file fails to be loaded, the dependencies on the file are different, and the errors triggered are inconsistent! Different levels.

Require (require_once): a fatal error is triggered, resulting in script termination;

Include (include_once): A warning error is triggered and the script continues to run.

The difference between require (include) and require_once (include_once:

Once indicates loading once. When loading, once will first judge whether the current file has been loaded.

Loaded: not loaded again

No load: execute the load!

Use require whenever possible.

Control script execution

Terminate script execution and delay script execution.

Die (), exit (): terminate the script execution. once it appears, the script is terminated immediately and all execution ends. In addition, a string can be output before the end.

Sleep (): Delay in script execution. pause for a period of time, in seconds. The maximum execution cycle is 30 seconds and can be configured. in the php. ini file, max_execution_time = 30

If some parameters in the parameter list have default values, but some do not, the default values are placed behind the parameter list.

Func_get_args (): Get all real parameters in the function.

$ GLOBALS: predefined variable

A pre-defined variable dedicated to over-regionalization of user data.

Different from other super global variables:

Each global variable automatically corresponds to an element in $ GLOBALS.

If you add a global variable, an element with the same name is automatically added to $ GLOBALS! And vice versa!

$ V1 = 10;

Var_dump ($ GLOBALS ['v1 ']);

$ GLOBALS ['V2'] = 20;

Var_dump ($ GLOBALS ['V2']);

The role of global is

Declare a local variable and initialize it as a reference to a global variable with the same name!

Functions of anonymous functions

Typical anonymous functions can be used as temporary functions. For example, some internal functions need to be called to complete the operation! For example: array_map (): returns an array = array_map ('function', array). you can use the provided functions to operate all the elements in an array!

Callback (callable) is required by passing an anonymous function!

PHP array pointer

Pointer functions

Php has the ability to obtain keys and values of array elements pointed to by pointers! Use functions:

Current () to obtain the value of the current element.

Key (): obtain the key of the current element. If the pointer is invalid, NULL is returned. Used to determine whether an element exists.

It should also have the ability to move pointers!

Next (): The pointer can be moved!

Array functions:

Range (): You can obtain an array of elements in a certain range.

Array_merge ('$ arr1', '$ arr2',...): merges arrays and merges multiple arrays.

What if the subscript is repeated?

Value Index: completely re-indexing!

Character subscript: the subsequent element value overwrites the previous element value!

Array_rand (array, number): randomly retrieves elements from the array and returns a subscript! If there are more than one, a set of random subobjects is returned! The result is sorted, from small to large!

Shuffle (& $ arr): disrupt the order of elements in the array. Note that the parameter is passed as a reference! Will disrupt the original array.

Key-value operation:

Array_keys (): gets all keys.

Array_values (): obtains all values.

In_array (): whether a value exists.

Array_key_exists (): whether a key exists.

Array_combine ('key array', 'value array'): combines two arrays into one array, one of which serves as the key and the other as the value!

Array_fill ('first index value', 'qty ', 'value'): fill the array.

Array = array_fill (starting subscript, number of filled elements, filled value );

Array_chunk (): splits an array. The principle is the number of elements in the subarray!

Array_intersect ($ arr1, $ arr2): calculates the intersection of two arrays and finds the elements that exist in $ arr1 and also exist in $ arr2, data appears in the first parameter.

Array_diff ($ arr1, $ arr2): calculates the difference set of the two arrays. Find the element that exists in arr1 but does not exist in arr2!

Array simulation stack and queue:

Queue and queue are both typical data structures and are a list type.

Stack Entry: array_push (), which pushes data into the array at the end of the array.

Output stack: array_pop (), which outputs elements at the top of the stack.

Array_push () and array_pop () are re-indexed to ensure that all elements increase one by one starting from 0.

Join: array_push (), which pushes data into the array at the end of the array.

Out of the queue: array_shift (), at the top of the array, the data is taken out.

Array_unshift (), you can press the data from the top of the array into the array.

Array sorting function

All sorting functions reference and pass values!

R: reverse, reverse. A: association. association. U: user.

Sort ('array'): sort values in ascending order without key-value Association.

Rsort ('array'): sort values in descending order without key-value Association.

Asort ('array'): maintains key-value Association in ascending order of values.

Arsort ('array'): maintains key-value Association in descending order of values.

Ksort ('array'): Sort keys and values in ascending order to maintain key-value Association.

Krsort ('array'): Sort keys and values in descending order to maintain key-value Association.

Natsort ('array'): sorts data using the calculated natural number!

Usort ('array'): custom sorting, the size relationship between user-defined elements. The user provides a function for comparing the sizes of two elements and can tell the size relationship of php elements. The user-defined function informs the size relationship between the two elements of usort (), and sorts the elements after usort obtains the relationship! Use the returned value to inform you!

Results returned in ascending order:

Returns a negative number, indicating that the first element is small;

Returns a positive number, indicating that the first element is large;

Returns 0, indicating equal.

The above introduces the basic PHP syntax knowledge, including the PHP syntax content, hope to be helpful to friends who are interested in the PHP Tutorial.

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.