search
HomeBackend DevelopmentPHP Tutorial详解PHP对数组的定义以及数组的创建方法_PHP

传统上把数组(array)定义为一组有某种共同特性的元素,这里的共同特性包括相似性(车模、棒球队、水果类型等)和类型(例如所有元素都是字符串或整数)等,每个元素由一个特殊的标识符来区分,这称为健(key)。请注意,上面这句话中的传统上一词,因为现在可以摒弃这种定义,数组结构中可以包括完全无关的元素。PHP则更进一步,数组中的元素甚至可以不属于同一种类型。例如,一个数组可能包含州名、邮政编码、考试成绩或扑克牌等元素。

每个实体包含两个项:前面提到的健(key)和值(value)。可以通过查询键来获取其相应的值。这些键可以是数值(numerical) 健或关联(associative)健。数值键与值没有真正的联系,它们只是值在数组中的位置。例如,一个数组中包含按字母顺序排列的水果名,键0表示apple,键2表示pear。使用PHP语法,该数组如下:

$fruits = array(
 "0"=>"apple",
 "1"=>"banana"
 "2"=>"pear"
 );

使用数组索引,可以如下引用第一个元素(apple):

$fruits[0]

PHP的数值索引组以位置0起始,而不是1。

与此不同的是,关联键与值有一定关系,而不是值在数组中的位置。使用数值索引值不可行时,以关联的方式来映射数组会特别方便。例如,你可能希望创建一个将水果缩写映射到水果名的数组,如AP/apple、BA/banana和PE/Pear。使用PHP语法,该数组如下:

$fruits = array(
 "AP"=>"apple",
 "BA"=>"banana",
 "PE"=>"pear"
 );

可以如下引用apple:

$fruits["AP"];

还可以创建包含数组的数组,这称为多维数组(multidimensional arrays)。例如,可以使用一个多维数组存储水果的信息。使用PHP语法,该数组如下:

$fruits = array(
  "apple"=>array(
 "name"=>"apple",
 "color"=>"red"
 ),
 "banana"=>array(
 "name"=>"banana",
 "color"=>"yellow"
 )
);

然后可以如下引用apple的color:

$states["apple"]["color"];

这将返回以下值:

red

你自然会想知道遍历数组的方法。PHP提供了很多遍历数组的方法。无论使用哪一种方法,要记住,它们都依赖于一种称为数组指针(array pointer)的特性。数组指针就如同书签,告诉你正在检查的数组位置。你并不是直接操作数组指针,而是使用内置的语言特性或函数来遍历数组。但是,理解这个基本概念很有用。


数组是PHP最重要的数据结构之一,数组在PHP的用处很广泛。与其他很多语言的数组实现方式不同,PHP不需要在创建数组时指定其大小。事实上,因为PHP是一种松散类型的语言,所以甚至不需要在使用数组前先行声明,尽管没有限制,PHP仍提供了正式和非正式的数组声明方法。两个方法各有优点,都值得学习。下面将分别讨论这两种方法,首先来介绍非正式的方法。

要引用PHP数组中的各个元素,可以用一对中括号来指示。因为数组没有大小限制,所以只需建立引用就可以创建数组,例如:

$fruits[0] = "apple";

然后,可以如下显示数组$fruits的第一个元素:

echo $fruits[0] = "apple";

接下来,可以为数组索引映射新值,从而添加其他的值,如下:

$fruits[1] = "banana";
$fruits[2] = "pear";

有趣的是,如果认为索引值是数组索引而且是递增的,还可以在创建时省略索引值:

$fruits[] = "apple";
$fruits[] = "banana";
$fruits[] = "pear";

用这种方式创建关联数组也同样很简单,只不过必须一直使用键。下面的实例创建了一个数组,它将水果映射到其颜色:

$fruits["apple"] = "red";
$fruits["banana"] = "yellow";
$fruits["pear"] = "yellow";

使用array()创建数组

array()函数接受0个或多个元素作为输入,返回一个包含这些收入元素的数组。其形式如下:

array array([item1,[,item2…[,itemN]]])

下面是一个使用array()创建索引数组的例子:

$fruits = array("apple","banana","pear");

还可以使用array()创建一个关联数组,如下:

$fruits = array(
 "AP"=>"apple",
 "BA"=>"banana",
 "PE"=>"pear"
 );

Statement
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
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

See all articles

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools