Home Backend Development PHP Tutorial PHP newbies on the road (4)_PHP tutorial

PHP newbies on the road (4)_PHP tutorial

Jul 21, 2016 pm 04:00 PM
php getting Started variable and string object support data array integer type

Getting Started with PHP

4.1 Data Types

PHP supports integers, floating point numbers, strings, arrays and objects. Variable types are usually not determined by the programmer but by the PHP runtime (what a relief!). Of course, if you like, you can also use cast or the function settype() to convert a variable of a certain type into a specified type.

Number

The numerical type can be an integer or a floating point number. You can use the following statements to assign a value to a value:
$a = 1234; # Decimal number
$a = -123; # Negative number
$a = 0123; # Octal number (equal to decimal number 83)
$a = 0x12; # Hexadecimal number (equal to 18 decimal numbers)
$a = 1.234; # Floating point number "double precision number"
$a = 1.2e3; # Double Exponential form of precision number

String

Strings can be defined by fields enclosed in single or double quotes. Note that the difference is that strings enclosed in single quotes are defined literally, while strings enclosed in double quotes can be expanded. Moreover, you can use backslash () in a double-quoted string to add escape sequences and conversion characters to the string. For example:

$first = 'Hello';
$second = "World";
$full1 = "$first $second"; # Generate Hello World
$full2 = ' $first $second';# produces $first $second
$full3="01DC studio,." 2000 copyright." " ;

 Please note the last line, if you need to use double quotes in the string , you can use the backslash character, as shown in this line of statements. The backslash here is used to change the functionality of double quotes.

Characters and numbers can be connected using arithmetic symbols. Characters are converted to numbers using their original position. There are detailed examples in the PHP manual.

Arrays and Hash Tables

Arrays and hash tables are supported in the same way. How you use them depends on how you define them. You can define them using list() or array(), or assign values ​​to arrays directly. The index of the array starts from 0. Although I haven't explained it here, you can easily use multidimensional arrays.

//An array containing two elements
$a[0] = "first";
$a[1] = "second";
$a[] = " third"; // Simple way to add array elements
// Now $a[2] is assigned the value "third"
echo count($a); // Print out 3 because the array has 3 elements Element
// Define an array with a statement and assign value
$myphonebook = array (
"sbabu" => "5348",
"keith" => "4829",
"carole" => "4533"
);
// Oh, forget about the dean, let's add an element
$myphonebook["dean"] = "5397";
// You defined the carale element wrong, let's correct it
$myphonebook["carole"] => "4522"
// Haven't I told you how to use similar support for arrays? Let's take a look at
echo "$myphonebook[0]"; // sbabu
echo "$myphonebook[1]"; // 5348

Some others useful for arrays or hash tables The functions include sort(), next(), prev() and each().

Object

Use the new statement to generate an object:
class foo
{
function do_foo ()
{
echo "Doing foo.";
}
}
$bar = new foo;
$bar->do_foo();

Change variable type

Mentioned in the PHP manual : "PHP does not support (and does not require) defining the variable type directly when declaring the variable; the variable type will be determined based on the situation in which it is used. If you assign the variable var to a string, then it becomes a string. If you assign an integer value to it, it becomes an integer. "

$foo = "0"; // $foo is a string (ASCII 48)
$foo++; / / $foo is the string "1" (ASCII 49)
$foo += 1; // $foo is now an integer (2)
$foo = $foo + 1.3; // $foo is a double Precision number (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is an integer (15)
$foo = 5 + "10 Small Pigs"; // $foo is an integer (15)

If you want to forcefully convert the variable type, you can use the same function settype() as in C language.

4.2 Variables and Constants

You may have noticed that variables are prefixed with a dollar sign ($). All variables are local variables. In order to use external variables in the defined function, use the global statement. And if you want to limit the scope of the variable to the function, use the static statement.
$g_var = 1; // Global scope
function test()
{
global $g_var; // This way global variables can be declared
}

More More advanced is the variable representation of variables. Please refer to the PHP manual. This can sometimes be useful.

PHP has many built-in defined variables. You can also use the define function to define your own constants, such as define("CONSTANT", "value").

4.3 Operators

PHP has the commonly seen operators in C, C++ and Java.The precedence of these operators is also consistent. Assignment also uses "=".

Arithmetic and characters

There is only one operator related to characters:
$a + $b: Add
$a - $b: Subtract
$ a * $b: Multiply
$a / $b: Divide
$a % $b: Modulo (remainder)
$a. $b: String concatenation

logical sum The comparison

logical operators are:
$a || $b: or
$a or $b: or
$a && $b: with
$a and $ b: with
$a xor $b: exclusive or (true when $a or $b is true, false when both are the same)
! $a: non-
comparison operators are:
$a == $b: equal
$a != $b: not equal
$a < $b: less than
$a <= $b: less than or equal to
$a > $b : Greater than
$a >= $b : Greater than or equal to
Like C, PHP also has a triple operator (?:). Bit operators also exist in PHP.

Priority

Just like C and Java!

4.4 Control flow structure

 PHP has the same flow control as C. I will briefly introduce it below.

if, else, elseif, if(): endif

if (expression one)
{
. . .
}
elseif (expression 2)
{
. . .
}
else
{
. . .
}
// Or like Python
if (expression 1) :
. . . .
. . .
elseif (Expression 2) :
. . . .
else :
. . . .
endif ;

Loops. while, do..while, for

while (expression)
{
. . .
}
do
{
. . .
}
while (expression);
for (expression one; expression two; expression three)
{
. . .
}
/ / Or like Python
while (expr) :
. . .
endwhile ;

switch

switch is the best for multiple if-elseif-else structures Replacement:
switch ($i)
{
case 0:
print "i equals 0";
case 1:
print "i equals 1";
case 2:
print "i equals 2";
}

break, continue

break breaks the current loop control structure.
continue is used to jump out of the remaining current loop and continue executing the next loop.

require, include

  Just like #include preprocessing in C. The file you specify in require will replace its location in the main file. When referencing a file conditionally, you can use include(). This allows you to split complex PHP files into multiple files and reference them separately when needed.

4.5 Function

You can define your own function like the following example. The return value of the function can be any data type:
function foo (variable name one, variable name two, . . . , variable name n)
{
echo "Example function.n";
return $retval;
}

All PHP code can appear in function definitions, even definitions of other functions and classes. Functions must be defined before being referenced.

4.6 Classes

Use class models to create classes. You can refer to the detailed explanation of classes in the PHP manual.
class Employee
{
var $empno; // Number of employees
var $empnm; // Employee name

function add_employee($in_num, $in_name)
{
$this->empno = $in_num;
$this->empnm = $in_name;
}

function show()
{
echo "$ this->empno, $this->empnm";
return;
}

function changenm($in_name)
{
$this->empnm = $ in_name;
}
}

$sbabu = new Employee;
$sbabu->add_employee(10,"sbabu");
$sbabu->changenm(" babu");
$sbabu->show();

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/317007.htmlTechArticleGetting Started with PHP 4.1 Data Types PHP supports integers, floating point numbers, strings, arrays and objects. Variable types are usually not determined by the programmer but by the PHP runtime (what a relief!). ...
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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
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 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 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.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

See all articles