Notes on PHP basic syntax, PHP basic syntax_PHP tutorial

WBOY
Release: 2016-07-13 10:13:16
Original
1079 people have browsed it

Notes on basic PHP syntax, basic PHP syntax

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: line break character (cross-platform portability, very important), will use different values ​​according to different operating systems. Line breaks vary between operating systems. window: rn *nix: n MAC: r

PHP_INT_MAX: The maximum value of shaping.

PHP_INT_SIZE: The number of bytes occupied by shaping.

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__: 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 as (__DIR__, this constant is new in PHP5.3)

__FUNCTION__: Magic constant to get 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 integer, once the value is too large, it will not overflow, but type conversion will occur and it will be converted to floating point type.

php does not support unsigned integers.

For example:

$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, but 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 a double quote, the variable will be parsed. If it is a single quote, it will not be parsed.

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

Case in which a variable is considered NULL

1. Is assigned the value NULL

2. Has not been assigned 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(): Print the details of the variable, including type and value.

gettype(): Get the type.

settype(): Set type.

is series: among which is_array() will be frequently used.

isset(): Checks whether a variable exists (sets).

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 the 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 part will be removed.

In the 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 other bits are inverted.

Complement code

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

For negative numbers, + 1 based on 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 the nth power of 2)

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 will always remain 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 the next loop body continues to execute.

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: When setting, the last setting will overwrite the previous setting!

Get the current include_path value

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

Use semicolons to connect directories.

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 the file loading 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): A warning error will be triggered 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!

Use require as much as possible .

Control script execution

Terminate script execution and delay script execution.

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

sleep(): Delay script execution 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 super-globalization of user data.

Different from other superglobal variables:

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

If you add a global variable, an element with the same name will be automatically added to $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 as a reference to the global variable with the same name!

The role of anonymous functions

Typical 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 obtain the key and value of the array element pointed to by the pointer! Utilization 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

Also should have: the ability to move the pointer!

next(): The pointer can be moved!

Array function:

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

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

What happens if the subscript is repeated?

Numerical indexing: Completely reindexed!

Character subscript: The element value appearing after 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 operation:

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'): utilizing two arrays Merge into an array with one as key and the other as value!

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

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

array_chunk(): When splitting an 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, data is present 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!

Array simulation stack and queue:

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

Push onto the stack: array_push(), push data into the array at the end of the array.

Pop from 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.

Enqueue: array_push(), push 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 from the top of the array into the array.

Array sorting function

The sorting functions are all passed by reference!

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

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

rsort('array'):                                                                                                                                                                                                                                 .

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

arsort('array'): 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!

Ascending order return effect:

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 equality.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/916827.htmlTechArticleNotes on PHP basic syntax, PHP basic syntax PHP constants: Predefined constants: PHP itself also defines a large number of predefined Constants can be viewed using get_defined_constants(). The more commonly used pre...
Related labels:
php
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