Home php教程 php手册 5种PHP创建数组的实例代码分享

5种PHP创建数组的实例代码分享

Jun 06, 2016 pm 08:25 PM
code share create Example array

在本文将数组的各种创建方式用PHP实例代码的方式分享给大家,感兴趣的朋友可以了解下

看这篇文章之前相信大家都已经看过PHP中文手册关于数组这一节的讲解了,怎么样呢,看懂了多少?至少我第一次阅读文档时是一头雾水,也许是因为在翻译的不够通俗易懂吧^_^!!这里UncleToo根据自己的经验,将数组的各种创建方式用PHP实例代码的方式分享给大家,希望对大家有些帮助(当然,,PHP文档还是要多看的)

1、使用array()创建数组

array()创建数组是我们在PHP开发过程中最常用到的一种方式,准确来说array()是一种结构而不是一个函数。

示例1:

复制代码 代码如下:


$number = array(1,3,5,7,9);
$color =array("red","blue","green");
$student = array("name",17)
?>


示例2:

复制代码 代码如下:


$language = array(1=>"PHP",3=>"JAVA",4=>"C");
$student = array("name"=>"张三","age"=>17)
?>


当然,数组里没有值也是允许的,即空数组:

复制代码 代码如下:


$result = array();
?>


2、使用compact()函数创建数组

PHP中compact()函数可以将一个或多个变量转换为数组

定义格式:

array compact(var1,var2...)

示例1:任何没有变量名与之对应的字符串都被略过。

复制代码 代码如下:


$firstname = "Peter";
$lastname = "Griffin";
$age = "38";
$result = compact("firstname", "lastname", "age");
print_r($result);
?>


输出结果:

复制代码 代码如下:


Array
(
[firstname] => Peter
[lastname] => Griffin
[age] => 38
)


示例2:使用没有对应变量名的字符串,以及一个变量名数组

复制代码 代码如下:


$firstname = "Peter";
$lastname = "Griffin";
$age = "38";
$name = array("firstname", "lastname");
$result = compact($name, "location", "age");
print_r($result);
?>


输出结果:

复制代码 代码如下:


Array
(
[firstname] => Peter
[lastname] => Griffin
[age] => 38
)


3、使用array_combine()函数创建数组

PHP中array_combine()函数可以将两个数组合并成一个新数组,其中的一个数组是键名,另一个数组的值为键值。

定义格式:

array array_combine(array1,array2)

示例

复制代码 代码如下:


$a1=array("a","b","c","d");
$a2=array("Cat","Dog","Horse","Cow");
print_r(array_combine($a1,$a2));
?>


输出结果:

Array ( [a] => Cat [b] => Dog [c] => Horse [d] => Cow )

注意:使用array_combine()函数时,两个参数必须有相同数目的元素。

4、使用range()函数创建数组

定义格式:

array range(first,second,step)

first:元素最小值

second:元素最大值

step:元素步长

下面是官方给的定义:该函数创建一个数组,包含从 first 到 second (包含 first 和 second)之间的整数或字符。如果 second 比 first 小,则返回反序的数组。

理解起来比较吃力,我们直接看例子(本人就喜欢看有例子的教程)。

示例1:

复制代码 代码如下:


$number = range(0,5);
print_r ($number);
?>


输出结果:

复制代码 代码如下:


Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
)


示例2:

复制代码 代码如下:


$number = range(0,50,10);
print_r ($number);
?>


输出结果:

复制代码 代码如下:


Array
(
[0] => 0
[1] => 10
[2] => 20
[3] => 30
[4] => 40
[5] => 50
)


示例3:

复制代码 代码如下:


$letter = range("a","d");
print_r ($letter);
?>


输出结果:

复制代码 代码如下:


Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)


5、使用array_fill()函数创建数组

array_fill()函数是用给定的值类填充数组

定义格式:

array_fill(start,number,value)

start:起始索引

number:数组个数

value:数组值

示例:

复制代码 代码如下:


$a=array_fill(2,3,"Dog");
print_r($a);
?>


输出结果:

Array ( [2] => Dog [3] => Dog [4] => Dog )
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 尊渡假赌尊渡假赌尊渡假赌

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)

How to remove duplicate elements from PHP array using foreach loop? How to remove duplicate elements from PHP array using foreach loop? Apr 27, 2024 am 11:33 AM

The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy May 01, 2024 pm 12:30 PM

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Jun 12, 2024 pm 08:38 PM

Since the launch of ChatGLM-6B on March 14, 2023, the GLM series models have received widespread attention and recognition. Especially after ChatGLM3-6B was open sourced, developers are full of expectations for the fourth-generation model launched by Zhipu AI. This expectation has finally been fully satisfied with the release of GLM-4-9B. The birth of GLM-4-9B In order to give small models (10B and below) more powerful capabilities, the GLM technical team launched this new fourth-generation GLM series open source model: GLM-4-9B after nearly half a year of exploration. This model greatly compresses the model size while ensuring accuracy, and has faster inference speed and higher efficiency. The GLM technical team’s exploration has not

PHP array multi-dimensional sorting practice: from simple to complex scenarios PHP array multi-dimensional sorting practice: from simple to complex scenarios Apr 29, 2024 pm 09:12 PM

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Apr 30, 2024 pm 03:42 PM

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

Create Agent in one sentence! Robin Li: The era is coming when everyone is a developer Create Agent in one sentence! Robin Li: The era is coming when everyone is a developer Apr 17, 2024 pm 02:28 PM

The big model subverts everything, and finally got to the head of this editor. It is also an Agent that was created in just one sentence. Like this, give him an article, and in less than 1 second, fresh title suggestions will come out. Compared to me, this efficiency can only be said to be as fast as lightning and as slow as a sloth... What's even more incredible is that creating this Agent really only takes a few minutes. Prompt belongs to Aunt Jiang: And if you also want to experience this subversive feeling, now, based on the new Wenxin intelligent agent platform launched by Baidu, everyone can create their own intelligent assistant for free. You can use search engines, smart hardware platforms, speech recognition, maps, cars and other Baidu mobile ecological channels to let more people use your creativity! Robin Li himself

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

See all articles