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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

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,

Top 10 Global Digital Virtual Currency Trading Platform Ranking (2025 Authoritative Ranking) Top 10 Global Digital Virtual Currency Trading Platform Ranking (2025 Authoritative Ranking) Mar 06, 2025 pm 04:36 PM

In 2025, global digital virtual currency trading platforms are fiercely competitive. This article authoritatively releases the top ten digital virtual currency trading platforms in the world in 2025 based on indicators such as transaction volume, security, and user experience. OKX ranks first with its strong technical strength and global operation strategy, and Binance follows closely with high liquidity and low fees. Platforms such as Gate.io, Coinbase, and Kraken are at the forefront with their respective advantages. The list covers trading platforms such as Huobi, KuCoin, Bitfinex, Crypto.com and Gemini, each with its own characteristics, but investment should be cautious. To choose a platform, you need to consider factors such as security, liquidity, fees, user experience, currency selection and regulatory compliance, and invest rationally

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

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.

See all articles