Home Backend Development PHP Tutorial PHP introductory tutorial common data types and basic syntax_PHP tutorial

PHP introductory tutorial common data types and basic syntax_PHP tutorial

Jul 13, 2016 am 10:50 AM
php Getting Started Tutorial and Basic Commonly used number data integer have float type grammar

The data types in PHP include integers, decimals (floating numbers), Boolean types, characters and arrays, variables, constants, etc. Let’s take a look.

One PHP common data types

1. Basic data types

1.1 integer
1.2 Decimal type (floating number) including single precision and double precision
1.3 Boolean type (representing true, and false)
1.4 String

2. Composite data type

2.1 Array (array)
2.2 Object

3. Special data types

3.1null
3.2 Resource type (resource)

2 Basic syntax of PHP

1. PHP defined variables must start with the $ symbol and are case-sensitive.
2. The name of the variable should start with a letter or an underscore, not a number, or a special character.

The first PHP program

The code is as follows Copy code
代码如下 复制代码
echo "Hello World!";
?>
echo "Hello World!"; ?>

1 Comment
1.1Multiple lines
/*
xxxx
*/
1.2 Single line
//xxxxx
2. Assignment
$a = 'test';
2.1 Check whether the variable has been declared
isset($a)
2.2 Release variables
unset($a);
2.3 Static variables
static $a;
Static variables can retain their value across several calls to a function without being released by the system, but they can only be accessed within the function set in which they are declared and can only be initialized the first time they are declared.
3. Basic types
3.1 Number type
3.1.1 Integer (integer, keyword int)
.Integers can be expressed in octal, decimal or hexadecimal
$a=123; //Decimal
$b=0123; //octal
$c=0x123; //16 hexadecimal
.Due to different operating systems, integer precision varies greatly, but 32-bit is the most common
3.1.2 Floating point (float, keyword float, 64-bit floating point number, 14-bit precision)
.float and double are equivalent in PHP
.When using floating point numbers remember: they are only approximations
For example: 2.5 is often expressed internally as 2.499999999
Another example:
if(0.7+0.1>=0.8){
echo 'a';
}else{
echo 'b';
}
The return value is b, which depends on the exact implementation of floating point numbers. The recommended practice is to avoid using floating point values ​​for comparison
3.2 String
.surround
with single or double quotes Such as: echo "Hello"; echo 'Hello';
.Variables in double quotes will be interpreted, but not in single quotes
For example: var $name = 'jano';
echo "my name is $name.";//Show my name is jano
echo 'my name is $name'; //Show my name is $name
.Variables in double quotes can be surrounded by {} to distinguish the variable from the following letters
For example: var $n = "my name is {$name}Yu"; //If there is no {}, variables and characters cannot be distinguished
.heredoc
$a = <<< HTM
skjdfjsd
lksdfjsdlf
HTML; //The following representation must be at the front
.Get a certain character in the string
$a = 'Hello';
echo $a{1}; // Display e
echo $a[1]; // Display e
It is recommended to use the first writing method to distinguish it from the array
3.3 Boolean value
true false
4. Commonly used functions
.nl2br converts the newline characters in the string into

Such as: echo nl2br($a);
.var_dump
Display variable type and value, such as: var_dump($a);
.print_r
Enhanced version of var_dump, prints object type and content, arrays print all elements, and class objects print all members
For example: $a = array(1,2,3,4,5);
print_r($a);
5.Array
Arrays are declared using the array method
Example:
$a = array('a','b','c');
$a = array('a','b',array(1,2,3));
.By default, assignment starts from index 0
For example: $a[]='a'; //$a[0]='a';
$a[]='b'; //$a[1]='b';
.Use string values ​​for indexing
Such as:
$a = array('car'=>'Ferrari','Number'=>21,'City'=>'CQ');
echo $a['car'];
.Traverse and change array element values ​​
foreach($array as $key=>&$value){// &$value
//...
}
6. Special types and values
.NULL is case-sensitive, meaning no value, never assigned, use unset to clear
.Resources
7. Forced type conversion
(int)$a
(float)$a
(string)$a
(bool)$a
(array)$a
(object)$a
.Special
(int)"0123";//Returns 123, without converting the octal number 0123 into a decimal number
(int)"123 mu tou ren";//return 123
(int)"mu tou ren 123";//returns 0, because the conversion only starts reading from the first character, and stops immediately when a non-digit is found
.convert to boolean
Non-empty and non-zero is true (including positive and negative numbers), 0 is false
An array containing 0 elements is false
NULL is false

Convert to integer
.Convert floating point to integer
Numbers after the decimal point are discarded. If the number of valid digits in the certificate is exceeded, the result may be 0 or the smallest negative number
.Boolean converted to integer
true is 1
false is 0
.Convert string to integer
Judge the first digit on the left side of the string. If the first digit is a number, the number read will be converted into an integer starting from the first digit. If the first digit is not a number the result is 0.
.PHP does not provide other methods for converting types to integers

Convert to floating point number
.Convert integer to floating point number
The result remains unchanged
.Boolean to float
true is 1
false is 0
.Convert string to floating point number
Similar to integers
.PHP does not provide other methods to convert to floating point numbers

Convert to string
The way to convert a non-string to a string is to use a "(string)" cast before the variable.
The rules are as follows:
1. Integer or floating point type: the result is its value
2. Boolean type: true is converted to '1', false is converted to an empty string
3. Object or array: If the variable being converted is an object or array, the conversion result will be a string object or string array, which needs to be analyzed according to the actual situation.
4. Resource type: Return resource identification number
8. Type judgment and acquisition

.convert to array
Use "(array)" to cast before the variable. Convert the variable to an array of the same data type as the member variable, with only one element in the array.
Such as:
$a=1;
print_r((array)$a);
Result:
Array
(
[0]=> 1
)

.convert to object
Use "(object)" to cast before the variable. A new object will be generated, in which the member variable named scalar will contain the value of the original variable. Such as:
$a=1;
$o = (object)$a;
echo $o->scalar;

Use functions for data conversion
bool settype(var, string type)

type value: boolean,integer,float,string,array,object,null

.Judge type function
is_integer Such as: is_integer($a); //Return true or false
is_float
is_double
is_real
is_int
is_long
is_numeric
is_string
is_bool
is_array
is_object
is_null
is_resource
is_scalar Is it a scalar
.Type get
gettype($a);
9. Variables and constants
.constant
define('NUM_USR','0');
$u = NUM_USR;
.Quote
$a=0;
$b = &$a;
$b++;
echo $a;//displays 1, because $b is a reference to $a, and a change in $b means a change in $a
10. Operator
10.1 Mathematical operators
+ - * / % (remainder)
10.2 Comparison operators
==
=== Same value, same type
!=
<> Same as !=, they are not equal to
!== Same value, different type
<
>
<=
>=
10.3 Logical operators
and && and
or || or
xor exclusive or, if one is true, but not both are true, the result is true
! Non
10.4 Bitwise operations
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise not
<< Shift left
>> Right shift
10.5 Ternary operator
Indicates whether the expression before the question mark is true. If so, the value before the colon will be returned. If not, the value after the colon will be returned
Such as:
$c = $a > $b ? 1:2;
echo $a>$b ? "hello":"no";
.The following two statements are equivalent
$a = ($b != 'china') ? true : false;
$a = $b != 'china';
10.6 Other operators
++ auto-increment
-- Decrease
@ Ignore errors when calling specific functions, such as: $u=@file(xxx);
. String concatenation operation, such as: $a = 'hello'.'world'; $a = 'hello'.$a;
11.7 Special logical operator expressions
$a = 0;
$b = 100;
echo $a || $b;//When $a is converted to a bool value of true, echo $a, otherwise echo $b, regardless of whether the $b expression is true, this expression will always display 100
echo $a && $b;//will display nothing because the entire expression $a && $b returns false
$a = 1;
$b = 0;
echo $a && $b;//will display nothing because the entire expression $a && $b returns false
echo $a && $b;//Always display $a
$a = 1;
$b = 0;
$a && $b=12;
echo $b;//displays 12, whether $a is true, if true, $b=12 will be executed. The system first reads &&, knowing that it is an AND, so it starts executing the statement before &&, and then executes it again if it returns true. If the statement after && is found to return false, the statement after && will no longer be executed. Because of the && logic, as long as there is a false, the entire expression will become false

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632632.htmlTechArticleThe data types in php include integers, decimals (floating numbers), Boolean types, characters and arrays, variables, Let’s take a look at the constants. 1 Commonly used data types in PHP 1. Basic data types...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

See all articles