Table of Contents
Explanation in this section
Preface
Introduction to arrays
Three ways to create arrays
Dynamic growth of arrays
Traversal of arrays
数组的相关函数
数组的运算符
总结
Home Backend Development PHP Tutorial PHP Basics Tutorial 8: Array

PHP Basics Tutorial 8: Array

Mar 01, 2017 am 09:48 AM

Explanation in this section

  • Introduction to arrays

  • Creation of arrays

  • Dynamic growth of array

  • Traversal of array

  • Related functions of array

  • Array Operator

Preface

What we have learned before is Variables and constants are individual pieces of data, and sometimes we have such a need to store some values ​​of the same type or some irrelevant values ​​reasonably, and when using them, they can be used according to certain rules Get the data. At this time, the previous variables cannot meet the requirements, so arrays are used here.

Introduction to arrays

Arrays in PHP are different from arrays in other languages. This is also caused by the looseness of PHP language syntax. What's the difference?

The so-called array is a collection of elements of the same data type or different data types arranged in a certain order. It is a collection of variables that names a limited number of variables with a name and then uses numbers to distinguish them. This name is called Array name, number is called subscript. The individual variables that make up an array are called components of the array, also called elements of the array, and sometimes called subscript variables.

The popular understanding of the definition of an array is to store a collection of data.

1

2

3

4

5

6

7

<?php

 

    //定义一个数组,里面存放的数据类型可以任意类型

    $arr = array(12,true,false,&#39;abcd&#39;,12.2);

    print_r($arr);//输出数组。

.....结果......

Array ( [0] => 12 [1] => 1 [2] => [3] => abcd [4] => 12.2 )

Copy after login

You can see that various data types are stored in the array, and they can be output during output. And you can see that when outputting, each value has a corresponding subscript. This subscript is called a key, and the value is a value. When we want to get a certain value, we can Get it by key.

1

2

3

4

$a = 数组名[键名]

echo $arr[0];

.....结果......

12

Copy after login

When the key value of the array is a number, its subscript is calculated from 0.

So how is the array created?

Three ways to create arrays

  • Index arrays (subscripts are numeric) There are three ways to define arrays in PHP.

  • Associative array (the subscript is a string)

  • The subscript of the array has both.

The first one

1

2

3

4

5

6

7

<?php

 

    //定义数组,数值用逗号隔开。

    $arr = array(1,2,3,4,&#39;abcd&#39;,true);

    print_r($arr);

.....结果......

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

Copy after login

Use the array() language structure to create a new array. You can see from the output that the subscript is a number. . The data is also retrieved through numerical subscripts. This is the index array.

The second one

1

2

3

4

5

6

7

<?php

 

    //关联数组,自己定义下标,用=>来定义键和值

    $arr = array(&#39;a&#39; => 1,&#39;b&#39; => 2,&#39;c&#39; => &#39;abcde&#39;, &#39;d&#39; => true);

    print_r($arr);

.....结果......

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

Copy after login

This method is also defined using the array() syntax structure, but the subscript of the array is defined by ourselves. Here we can Define the subscript for your own situation. Regarding the key value definition, please note that the key will have the following forced conversion

  1. Strings containing legal integer values ​​will be converted to integers. For example, the key name "8" will actually be stored as 8. But "08" will not be cast because it is not a legal decimal value.

  2. Floating point numbers will also be converted to integers, which means their decimal parts will be rounded off. For example, the key name 8.7 will actually be stored as 8.

  3. Boolean values ​​will also be converted to integers. That is, the key name true will actually be stored as 1 and the key name false will be stored as 0.

  4. Null will be converted into an empty string, that is, the key name null will actually be stored as "".

  5. Arrays and objects cannot be used as keys. Insisting on doing this will result in a warning: Illegal offset type.

If multiple units use the same key name in the array definition, only the last one will be used, and the previous ones will be overwritten.

To get the value in the associative array, you need to use your own defined key to get it.

The third type

1

2

3

4

5

6

7

8

9

10

<?php

 

    $arr[0] = 1;

    $arr[2] = 2;

    $arr[&#39;a&#39;] = 12;

    $arr[4] = 45;

 

    print_r($arr);

.....结果......

Array ( [0] => 1 [2] => 2 [a] => 12 [4] => 45 )

Copy after login

The definition of the third type of array can be defined directly using square brackets. The system will default to thinking that this is an array and create it. For subscripts you can use numbers or strings. But if multiple units use the same key name in the array definition, only the last one is used, and the previous ones are overwritten.

Dynamic growth of arrays

The length of PHP’s array is not fixed. When you finish filling in the data, you can still fill in the data. At the same time, the array The length will also increase accordingly. This is the dynamic growth of the php array.

1

2

3

4

5

6

7

8

<?php

 

    for($i = 0; $i < 10; $i++){

        $arr[] = $i;

    }

    print_r($arr);

......结果.......

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 )

Copy after login

The above code uses a for loop and uses the third definition method of the array to assign values. However, you can see that we did not write the subscript in the square brackets of the array, but the program did not report an error. This It's because of the dynamic growth of the array. If a key value is not specified, PHP will automatically use the largest previously used integer key plus 1 as the new key. Therefore, you can see in the output that the subscript automatically increases from 0.

Traversal of arrays

We introduced the creation and basic use of arrays earlier, so how do we remove all the values ​​​​from the array? In PHP, you can use a loop control process to get the values ​​in an array, and loop through the array to get the values ​​inside one by one.

for

You can use for to get the values ​​in the array during array traversal.

1

2

3

4

5

6

7

8

9

<?php

 

    $arr = array(1,9,4,2,8,10,5);

    $sum = count($arr);

    for($i = 0; $i < $sum; $i++){

        echo $arr[$i] . &#39;  &#39;;

    }

.....结果......

1 9 4 2 8 10 5

Copy after login

上面的count()这个系统函数是统计一个数组里的所有元素,或者一个对象里的东西。从而的到数组的大小,也就是长度。然后通过for循环,把$i当做数组的下标($i从0开始)。

foreach

在上面的代码中如果我们的数组是关联数组,也就是数组的下标是一个字符串,那么上面的代码是不可能取出来。所以我们可以使用PHP提供的另外一种循环方法:foreach()。它的语法有两种:

1

2

3

4

5

6

7

foreach(数组名 as $key => $value){

 

}

 

foreach(数组名 as $value){

 

}

Copy after login

其中“as”是一个关键字,不能变。

foreach里面有可以有三个参数,第一个参数是数组的名字,第二个参数

value是用来存储从数组中取出来的值。当然键和值得名字可以根据自己的情况自己取。

当里面的参数是两个的时候,$value只用来存放从数组中取出来的值,而没有键。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<?php

 

    $arr = array(1,9,4,2,8,10,5);

 

    foreach ($arr as $key => $value) {

        echo $key . &#39;=>&#39; . $value . &#39;  &#39;;

    }

 

    echo &#39;<br>&#39;;

 

    foreach ($arr as $value) {

        echo $value . &#39;  &#39;;

    }

.....结果......

0=>1 1=>9 2=>4 3=>2 4=>8 5=>10 6=>5

1 9 4 2 8 10 5

Copy after login

在第二个循环中没有键的输出。

上面的两种循环结构,就是我们常用到的数组遍历的方法,其中第二个方法,也就是用foreach的方法,我们会经常用到,因为这种方法对于所有的数组都适用,而不用考虑下标的问题。

数组的相关函数

  • count($array) 统计一个数组里的所有元素,或者一个对象里的东西。从而的到数组的大小,也就是长度。然后通过for循环,把

    i从0开始)。

  • is_array($arr) 判断变量是否是一个数组。传一个变量进去,如果这个变量是一个数组,则返回true,否则则返回false;

  • array_search (value) 在数组中搜索给定的值,如果成功则返回相应的键名 。当我们想知道一个数组中有没有一个数,可以使用这个函数,如果数组中有你想找的值,则返回这个值对应的键值。

  • array_reverse($arr),传进去一个数组,返回一个与这个数组相反的数组。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    <?php

     

    $arr = array(1,9,4,2,8,10,5);

     

    $array = array_reverse($arr);

     

    print_r($array);

    .....结果......

    Array ( [0] => 5 [1] => 10 [2] => 8 [3] => 2 [4] => 4 [5] => 9 [6] => 1 )

    Copy after login
  • array_merge($arr1,$arr2),传进去两个数组,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。 如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。

  • unset($value) 传进去的变量可以销毁一个数组,也可以销毁数组中的一个值,当通过数组[下标]的方式传入是,会销毁数组中的这个值,但是当传进去的数组时,会把整个数组进行销毁。

  • sort() 本函数对数组进行排序。当本函数结束时数组单元将被从最低到最高重新安排。当数组中值都是数字的时候,可以使用这个函数进行排序,不过排序的结果是数字按照从小到大的顺序。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    <?php

     

        $arr = array(1,9,4,2,8,10,5);

     

        sort($arr);

     

        print_r($arr);

    .....结果.....

    Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 5 [4] => 8 [5] => 9 [6] => 10 )

    Copy after login
  • usort($array,func_name) 传进去一个数组,和一个自己写的方法名。使用用户自定义的比较函数对数组中的值进行排序,在上面的一个方法,你只能得到从小到大的顺序,但是我们的要求是从大到小,这就会用到这个函数,第二个参数是我们写的排序规则的函数。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    <?php

     

    $arr = array(1,9,4,2,8,10,5);

     

    function mysort($a,$b){ //写自己的函数,使数组按照从大到小的顺序进行排序。

    if($a == $b){

        return 0;

    }

     

        return $a < $b ? 1 : -1;

    }

     

    usort($arr, &#39;mysort&#39;);

     

    print_r($arr);

    ......结果......

    Array ( [0] => 10 [1] => 9 [2] => 8 [3] => 5 [4] => 4 [5] => 2 [6] => 1 )

    Copy after login

    这里使用到可变函数。

    数组的运算符

    我们在运算符那一节并没有讲到数组的运算符,其实数组也是有运算符的。

    • $a + $b 联合 $a 和 $b 的联合。运算符把右边的数组元素附加到左边的数组后面,两个数组中都有的键名,则只用左边数组中的,右边的被忽略。

    • $a == $b 相等 如果 $a 和 $b 具有相同的键/值对则为 TRUE 。

    • $a === $b 全等 如果 $a 和 $b 具有相同的键/值对并且顺序和类型都相同则为 TRUE 。

    • $a != $b 不等 如果 $a 不等于 $b 则为 TRUE 。

    • $a <> $b 不等 如果 $a 不等于 $b 则为 TRUE 。

    • $a !== $b 不全等 如果 $a 不全等于 $b 则为 TRUE 。  
      在这里看来数组的运算符也是很好理解的。

    总结

    数组讲到这里,算是基本讲完了,数组在我们的开发中是经常用到的,不止上面的以为数组,有时候数组里面还可能是一个数组,只要数组的结构在脑海中有清晰的认识,不管有几个数组,都是可以解决的,同时数组的出现也引出了一些关于数组的算法。

     以上就是PHP基础教程八之数组的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
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,

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

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.

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

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.

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: 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.

See all articles