Basic syntax knowledge of PHP

WBOY
Release: 2016-08-08 09:33:10
Original
1276 people have browsed it

PHP (foreign name: Hypertext Preprocessor, Chinese name: "Hypertext Preprocessor") is a general open source scripting language. The syntax absorbs the characteristics of C language, Java and Perl, which is easy to learn and widely used. It is mainly suitable for the field of Web development.

PHP’s unique syntax mixes C, Java, Perl and PHP’s own syntax. It can execute dynamic web pages faster than CGI or Perl. Compared with other programming languages, dynamic pages made with PHP embed programs into HTML (an application under the Standard Universal Markup Language) document for execution, and the execution efficiency is much higher than CGI that completely generates HTML tags; PHP can also execute compiled code. Compilation can achieve encryption and optimize code running, making the code run faster.

PHP constants:

Predefined constants:

PHP itself also defines a large number of predefined constants, which can be viewed using get_defined_constants(). The more commonly used predefined constants are:

PHP_OS: PHP system.

PHP_VERSION: PHP version.

PHP_EOL: Newline character (cross-platform portability, very important), different values ​​will be used according to different operating systems. Line breaks vary between operating systems. window: rn *nix: n MAC: r

PHP_INT_MAX: The maximum value of integer.

PHP_INT_SIZE: The number of bytes occupied by the integer.

PATH_SEPARATOR: The separator between paths in environment variables.

DIRECTORY_SEPARATOR: Directory separator. Both '' and '/' are available under window, while *nix can only use '/'.

Magic constants:

It looks like a constant but is actually a non-constant. Its syntax is similar to a constant. It is called a magic constant!

__FILE__: The complete file path and file name. Typical applications (project codes) such as:

define('ROOT_PATH',str_replace('7.php','',__FILE__));

echo ROOT_PATH;

The result is the same (__DIR__, this constant is new in PHP5.3)

__FUNCTION__: Get the magic constant of the current function name!

PHP base conversion

In PHP, a series of functions are provided for base conversion:

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

For example: decbin(), converts a decimal number into a binary number; octhex() converts an octal number into a hexadecimal number.

For integers, once the value is too large, it will not overflow, but type conversion will occur and it will be converted to a floating point type.

PHP does not support unsigned integers.

like:

$a = PHP_INT_MAX; //2147483648

$b = $a+1;

var_dump($b); //float

In php, float, double are actually the same. Floating point numbers have a precision of 14 decimal digits, with a maximum value that is platform-dependent, typically 1.8e308. The comparison of floating point numbers is unreliable. When writing a program, don't try to get business logic by comparing two floating point numbers for equality.

How strings are defined

There are four ways to define strings: double quotes, single quotes, heredoc (delimiter), nowdoc (delimiter)

Double quotes can parse variables, single quotes cannot parse variables. Single quotes can contain double quotes, and double quotes can contain single quotes, but quotes cannot contain quotes themselves.

Whether a variable can be parsed does not depend on which one the variable is included in, but depends on whether the definition string is single or double quotes. If it is double quotes, the variable will be parsed. If it is single quotes, it will not be parsed.

In a string, if there are {$ connected together, it means that the {} in it is parsed as a variable.

When a variable is considered NULL

1. Is assigned a value of NULL

2. Has not been assigned a value yet

3. Being unset()

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

Data type related functions

var_dump(): Prints detailed information about variables, including type and value.

gettype(): Get the type.

settype(): Set type.

is series: is_array() is often used.

isset(): Check whether a variable exists (set).

empty() : Checks whether a variable is empty.

For isset(), as long as it is declared (has a value), no matter what its value is, it will return true.

For empty(), it is equivalent to boolean (variable), and then negated.

Conversion to Boolean is considered FALSE

1.Boolean value FALSE itself

2. Integer value 0 (zero)

3. Floating point value 0.0 (zero)

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

5. Empty array

6. Special type NULL (including variables that have not been set)

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

PHP operation rules

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

In the modulo operation, if there are decimals, the decimal parts will be removed.

In a modulo operation, the sign of the result depends on the first number.

Original code

Convert decimal to binary. The highest bit is used to represent the sign bit, 0 represents a positive number, and 1 represents a negative number.

reverse code

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

For negative numbers, the sign bit remains unchanged and the other bits are inverted.

complement

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

For negative numbers, add 1 to the complement.

The symbol remains unchanged during transcoding, and the symbol bit participates in the operation during operation.

Shift operation

Right shift: The low bit overflows, the sign bit remains unchanged, and the high bit is completed with the sign bit (equivalent to dividing by 2 to the nth power, and then rounding)

Left shift: the high bit overflows, the sign bit remains unchanged, and the low bit is filled with 0 (equivalent to multiplying by 2 raised to the nth power)

Whether it is a left shift or a right shift, it will only change the size of the number but not the sign, so during the shift operation, the sign bit is always unchanged.

PHP operator precedence

The difference between and or and && ||.

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

break: terminate. When break is executed, the entire loop loop statement ends directly.

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

include and require

Set the value of include_path

Use the function set_include_path().

set_include_path('d:/php/test'); then directly require 'file.php',

Note: During setting, the last setting will overwrite the previous setting!

Get the current include_path value

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

Directories are connected using semicolons.

set_include_path('d:/php/test'.PATH_SEPARATOR.get_include_path());

PHP compiles the code in source file units. If there is a syntax error in the current file, PHP will report an error. Code compilation processing will not be performed.

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

When loading a file fails, the dependencies on the file are different and the errors triggered are inconsistent! The levels are different.

require(require_once): will trigger a fatal error, causing the script to terminate;

include(include_once): will trigger a warning error and the script will continue to run.

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

With once means loading once. When loading, the one with once will first make a judgment on whether the current file has been loaded.

Already loaded: will not be loaded again

Not loaded: Perform loading!

Just use require as much as possible.

Control script execution

Terminate script execution and delay script execution.

die(), exit(): Terminate script execution. Once it occurs, the script terminates immediately and ends all execution. And you can output a string before ending.

sleep(): Delay script execution and pause for a period of time, in seconds. The maximum execution period 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, then the parameters with default values ​​will be placed after the formal parameter list.

func_get_args(): Get all the actual parameters in the function.

$GLOBALS: predefined variables

A predefined variable specifically for superglobalization of user data.

Unlike other superglobal variables:

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

Adding a global variable will automatically add an element with the same name in $GLOBALS! vice versa!

$v1 = 10;

var_dump($GLOBALS['v1']);

$GLOBALS['v2'] = 20;

var_dump($GLOBALS['V2']);

The function of global is

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

The role of anonymous functions

Typically anonymous functions can be used as temporary functions. For example, some internal functions need to call a certain function to complete the operation! Like: array_map(): Return array = array_map('function', array); Use the provided function to operate on all elements in an array!

Wherever parameters require callback (callable), this is done by passing anonymous functions!

PHP array pointer problem

pointer function

PHP has: the ability to get the key and value of the array element pointed to by the pointer! Utilize function:

current(), get the value of the current element

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

There should also be: the ability to move the pointer!

next(): can complete the movement of the pointer!

Array functions:

range(): You can get an array of elements within a certain range.

array_merge('$arr1','$arr2',...): Merge arrays, merge multiple ones.

What happens if the subscript is repeated?

Numeric indexing: Complete re-indexing!

Character subscript: The element value appearing later will overwrite the previous element value!

array_rand (array, number): Randomly obtain elements from the array, and obtain the subscript! If there are multiple, return a set of random subscripts! The results are sorted, from small to large!

shuffle(&$arr): shuffle the order of elements in the array. Note that parameters are passed by reference! Will disrupt the original array.

Key value operations:

array_keys(): Get all keys.

array_values(): Get all values.

in_array(): Whether a certain value exists.

array_key_exists(): Whether a key exists.

array_combine('key array', 'value array'): Use two arrays to merge into one array, one as the key and the other as the value!

array_fill('first index value','number','value'): Fill the array.

Array = array_fill(starting index, number of elements to fill, value to fill);

array_chunk(): split the array, the principle is the number of elements in the sub-array!

array_intersect($arr1, $arr2): Calculate the intersection of two arrays and find the elements that exist in $arr1 and also exist in $arr2. The data appears in the first parameter.

array_diff($arr1, $arr2): Calculate the difference between two arrays. Find elements that exist in arr1 but do not exist in arr2!

Arrays simulate stacks and queues:

Both 桟 and queue are typical data structures, and both are a type of list list.

Pushing onto the stack: array_push(), pushes data into the array at the end of the array.

Pop off the stack: array_pop(), output elements on the top of the stack.

array_push() and array_pop() will re-index to ensure that all elements start from 0 and increase one by one.

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

Dequeue: array_shift(), take out the data at the top of the array.

array_unshift() can push data into the array from the top of the array.

Array sort function

Sorting functions are all passed by reference!

r: reverse, reverse. a: association, association. u: user, user-defined.

sort('array'): Sort by value, in ascending order, without maintaining key-value association.

rsort('array'): Sort by value, in descending order, without maintaining key-value association.

asort('array'): Sort by value in ascending order, maintaining key-value association.

arsort('array'): Sort by value, in descending order, maintaining key-value association.

ksort('array'): Sort by key in ascending order, maintaining key-value association.

krsort('array'): Sort by key, in descending order, maintaining key-value association.

natsort('array'): Natural number sorting, you can use the calculated natural numbers to sort the data!

usort('array'): Custom sorting, user-defined size relationship between elements. The user provides a function that compares the sizes of two elements and can tell PHP the size relationship of the elements. The function defined by the user is responsible for telling usort() the size relationship between the two elements, and usort is responsible for completing the sorting after getting the relationship! Use the return value to inform!

Return effect in ascending order:

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

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

Returns 0, indicating equality.

The above introduces the basic syntax knowledge of PHP, including the content of PHP syntax. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template