Table of Contents
1. Array definition
2. Create array
3. Array traversal
4. Array pointer operations
5. Array addition and deletion operations
6. Array key and value operations
7. Sorting of arrays
8. 数组的其他用法
总结
Home Backend Development PHP Tutorial Important: Summary of various operations and functions of PHP arrays_PHP Tutorial

Important: Summary of various operations and functions of PHP arrays_PHP Tutorial

Jul 13, 2016 am 10:32 AM
php array

For Web programming, the most important thing is accessing, reading and writing data. There may be many storage methods, including strings, arrays, files, etc. Arrays can be said to be one of the more important methods in PHP data applications. There are many array functions in PHP. The following is a summary of what I learned so that I can learn from them in the future.

1. Array definition

The definition of an array is defined using the array() method. You can define an empty array:

<?php
    $number = array(1,3,5,7,9);
    //定义空数组
    $result = array();
    $color =array("red","blue","green");
    //自定义键值
    $language = (1=>"English",3=>"Chinese",5=>"Franch");
    //定义二维数组
    $two = array(
                "color"=>array("red","blue"),    //用逗号结尾
                "week"=>array("Monday","Friday")    //最后一句没有标点
    );
?>
Copy after login

2. Create array

compact()

compact() function - Convert one or more variables (including arrays) into arrays: array compact (mixed $varname [, mixed $... ]).

<?PHP
    $number = "1,3,5,7,9";
    $string = "I'm PHPer";
    $array = array("And","You?");
    $newArray = compact("number","string","array");
    print_r ($newArray);
?>
Copy after login

The compact() function is used to convert two or more variables into arrays, including array variables of course. The parameter is the name of the variable rather than the full name with $. The opposite function is extract(). As the name suggests, it converts the array into a single string, with the key value as its string name and the array value as the string value.

Run results:

Array ( 
	[number] => 1,3,5,7,9 
	[string] => I'm PHPer 
	[array] => Array ( [0] => And [1] => You? ) 
)
Copy after login

array_combine()

array_combine() - Reorganize two arrays into one array, one as a key value and the other as a value: array array_combine (array $keys, array $values)

<?PHP
    $number = array("1","3","5","7","9");
    $array = array("I","Am","A","PHP","er");
    $newArray = array_combine($number,$array);
    print_r ($newArray);
?>
Copy after login

I won’t go into details about the array_combine function, everyone will understand it after reading it.

Run result:

Array ( [1] => I [3] => Am [5] => A [7] => PHP [9] => er )
Copy after login

range()

range() function - creates an array within a specified range:

<?PHP
    $array1 = range(0,100,10);//0为起始值,100为结束值,10为步进值(默认步进值为1).
    print_r($array1);
    echo"<br />";
    $array2 = range("A","Z");
    print_r($array2);
    echo "<br />";
    $array3 = range("z","a");
    print_r($array3);
?>
Copy after login

array_fill()

array_fill() function - fill array function:

<?PHP
        $array = range(1,10);
        $fillarray = range("a","d");
        $arrayFilled = array_fill(0,5,$fillarray);//这里的$fillarray可以是字符串,如"test".
        echo "<pre class="brush:php;toolbar:false">";
        print_r ($arrayFilled);
        echo "
"; $keys = array("string","2",9,"SDK","PK"); $array2 = array_fill_keys($keys,"testing"); echo "
";
        print_r ($array2);
        echo "
"; ?>
Copy after login

Run result:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] => c
            [3] => d
        )
    [1] => Array
        (
            [0] => a
            [1] => b
            [2] => c
            [3] => d
        )
    [2] => Array
        (
            [0] => a
            [1] => b
            [2] => c
            [3] => d
        )
    [3] => Array
        (
            [0] => a
            [1] => b
            [2] => c
            [3] => d
        )
    [4] => Array
        (
            [0] => a
            [1] => b
            [2] => c
            [3] => d
        )
)
Array
(
    [string] => testing
    [2] => testing
    [9] => testing
    [SDK] => testing
    [PK] => testing
)
Copy after login

3. Array traversal

foreach traversal

foreach (array_expression as $value){}

foreach (array_expression as $key => $value){}

<?PHP
	$speed = array(50,120,180,240,380);
	foreach($speed as $keys=>$values){
		echo $keys."=>".$values."<br />";
	}
?>
Copy after login

Run result:

0=>50
1=>120
2=>180
3=>240
4=>380
Copy after login

while loop traversal

While loop traversal is generally combined with the list function. The following is an example

	<?PHP
        $staff = array(
            array("姓名","性别","年龄"),
            array("小张","男",24),
            array("小王","女",25),
            array("小李","男",23)
        );
        echo "<table border=2>";
        while(list($keys,$value) = each($staff)){
            list($name,$sex,$age) = $value;
            echo "<tr><td>$name</td><td>$sex</td><td>$age</td></tr>";
        }
        echo "</table>";
       ?>
Copy after login

for loop traversal

<?PHP
    $speed = range(0,220,20);
    for($i =0;$i<count($speed);$i++) {
        echo $speed[$i]." ";
    }
?>
Copy after login

Run result:

0 20 40 60 80 100 120 140 160 180 200 220 
Copy after login

4. Array pointer operations

Involved functions include reset, prev, end, next, current, and each.

Example 1: next and prev

<?PHP
    $speed = range(0,220,20);
    echo current($speed);//输出当前位置的值(在数组的开头位置)
    $i = rand(1,11);
    while($i--){
        next($speed);//指针从当前位置向后移动一位
    }
    echo current($speed);//输出当前位置的值
    echo "<br />";
    echo prev($speed);//输出前一位置数组值
    echo "<br />";
    echo reset($speed);//重置数组的指针,将指针指向起始位置
    echo "<br />";
    echo end($speed);//输出最后位置的数组值
    echo "<br />";
?>
Copy after login

Run result:

0220
200
0
220
Copy after login

Example 2: each function pointer operation

<?PHP
    $speed = range(0,200,40);
    echo "each实现指针下移 <br />";
    echo "0挡的速度是".current(each($speed))."<br />";
    echo "1挡的速度是".current(each($speed))."<br />";
    echo "2挡的速度是".current(each($speed))."<br />";
    echo "3挡的速度是".current(each($speed))."<br />";
    echo "4挡的速度是".current(each($speed))."<br />";
    echo "5挡的速度是".current(each($speed))."<br />";
    echo "使用each函数实现数组指针的移动,进行数组遍历 <br />";
    reset($speed);//这里是将数组指针指向数组首
    while(list($key,$value)=each($speed)){
        echo $key."=>".$value."<br />";
    }
?>
Copy after login

Run result:

each实现指针下移 
0挡的速度是0
1挡的速度是40
2挡的速度是80
3挡的速度是120
4挡的速度是160
5挡的速度是200
使用each函数实现数组指针的移动,进行数组遍历 
0=>0
1=>40
2=>80
3=>120
4=>160
5=>200
Copy after login

5. Array addition and deletion operations

Add array members

Example 1: $num[] = value is directly assigned and appended to the end of the array:

	<?PHP
        $num = array(1=>80,2=>120,3=>160);
        echo "使用表达式添加数组成员<br />";
        $num[]=240;
        print_r($num);
      ?>
Copy after login

Run result:

使用表达式添加数组成员
Array ( [0] => 80 [1] => 120 [2] => 160 [3] => 240 )
Copy after login

Example 2: array_pad function, selective appending of the beginning and end of an array

	<?PHP
        $num = array(1=>80,2=>120,3=>160);
        $num = array_pad($num,4,200);
        echo "使用array_pad函数向数组尾部添加成员<br />";
        print_r($num);
        echo "<br />array_pad 还可以填充数组首部<br />";
        $num = array_pad($num,-8,40);
        print_r($num);
    ?>
Copy after login

Run result:

使用array_pad函数向数组尾部添加成员
Array ( [0] => 80 [1] => 120 [2] => 160 [3] => 200 ) 
array_pad 还可以填充数组首部
Array ( [0] => 40 [1] => 40 [2] => 40 [3] => 40 [4] => 80 [5] => 120 [6] => 160 [7] => 200 )
Copy after login

Example 3: Add push operation (array_push):

	<?PHP
        $num = array(1=>80,2=>120,3=>160);
        array_push($num,200,240,280);//可以自己追加,直接加在数组结尾
        print_r($num);
    ?>
Copy after login

Run result:

Array ( [1] => 80 [2] => 120 [3] => 160 [4] => 200 [5] => 240 [6] => 280 )
Copy after login

Example 4: array_unshift() adds array members at the beginning

	<?PHP
        $num = array(1=>80,2=>120,3=>160);
        array_unshift($num,0,40);//可以自己追加,直接加在数组结尾
        print_r($num);
    ?>
Copy after login

Run result:

Array ( [0] => 0 [1] => 40 [2] => 80 [3] => 120 [4] => 160 )
Copy after login

Note: After using the array_unshift() function, the key value of the array will start from 0!

Delete array members

Example 1: The unset() command deletes array members or arrays:

	<?PHP
        $num = array_fill(0,5,rand(1,10));
        print_r($num);
        echo "<br />";
        unset($num[4]);
        print_r($num);
        echo "<br />";
        unset($num);
        if(is_array){
            echo "unset命令不能删除整个数组";
        }else{
            echo "unset命令可以删除数组";
        }
    ?>
Copy after login

Running result: (Run error and description array are also deleted and no longer exist)

Array ( [0] => 9 [1] => 9 [2] => 9 [3] => 9 [4] => 9 ) 
Array ( [0] => 9 [1] => 9 [2] => 9 [3] => 9 ) 
Notice: Use of undefined constant is_array - assumed 'is_array' in H:\wamp\www\testing\editorplus\test.php on line 21
unset命令不能删除整个数组
Copy after login

Example 2: array_splice() function deletes array members

<?php
        $a=array("red", "green", "blue", "yellow");   
        count ($a); //得到4   
        array_splice($a,1,1); //删除第二个元素   
        count ($a); //得到3   
        echo $a[2]; //得到yellow   
        echo $a[1]; //得到blue   
?>   
Copy after login

Example 3: array_unique deletes duplicate values ​​in the array:

	<?php
        $a=array("red", "green", "blue", "yellow","blue","green");   
        $result = array_unique($a);
        print_r($result);
    ?>
Copy after login

Run result:

Array ( [0] => red [1] => green [2] => blue [3] => yellow )
Copy after login

Example 4: array_merge, array_merge_recursive merge arrays

	<?php
        $array1 = array("r"=>"red",1,2,3,4);
        $array2 = array("b"=>"blue",4=>5,6,7,8,9);
        $array3 = array("r"=>"read",4=>10,2=>11);
        $array4 = array(
            array(4=>10),
            array(7=>13)
        );
        $array5 = array(
            array(4=>11),
            array(6=>12)
        );
        $result = array_merge($array1,$array2,$array3,$array4,$array5);
        echo "<pre class="brush:php;toolbar:false">";
        print_r($result);
        echo "
"; $result = array_merge_recursive($array1,$array2,$array3,$array4,$array5); echo "
";
        print_r ($result);
        echo "
"; ?>
Copy after login

Run result:

Array
(
    [r] => read
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [b] => blue
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
    [11] => Array
        (
            [4] => 10
        )
    [12] => Array
        (
            [7] => 13
        )
    [13] => Array
        (
            [4] => 11
        )
    [14] => Array
        (
            [6] => 12
        )
)
Array
(
    [r] => Array
        (
            [0] => red
            [1] => read
        )
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [b] => blue
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
    [11] => Array
        (
            [4] => 10
        )
    [12] => Array
        (
            [7] => 13
        )
    [13] => Array
        (
            [4] => 11
        )
    [14] => Array
        (
            [6] => 12
        )
)
Copy after login

Note: 1. If the key name of array_merge is numeric, the index will be re-established; when the same string key name is encountered, the later one will overwrite the previous one. 2. The function of array_merge_recursive function is to integrate the key name units of the same string into an array.

6. Array key and value operations

Example 1: in_array() detects whether a certain value exists in the array

	<?php
        $array = range(0,9);
        if(in_array(9,$array)){
            echo "数组中存在";
        }
    ?>   
Copy after login

Run result:

exists in the array

Example 2: key() gets the current key name of the array:

	<?php
        $array = range(0,9);
        $num = rand(0,8);
        while($num--)
        next($array);
        $key = key($array);
        echo $key;
    ?>
Copy after login

The results of this example are dynamic results, range (0-8), and no result demonstration is performed.

Example 3: The list() function assigns the values ​​in the array to the specified variable:

<?PHP
        $staff = array(
            array("姓名","性别","年龄"),
            array("小张","男",24),
            array("小王","女",25),
            array("小李","男",23)
        );
        echo "<table border=2>";
        while(list($keys,$value) = each($staff)){
            list($name,$sex,$age) = $value;
            echo "<tr><td>$name</td><td>$sex</td><td>$age</td></tr>";
        }
        echo "</table>";
?>
Copy after login

Example 4: array_flip() exchanges the key and value of the array:

	<?PHP
        $array = array("red","blue","yellow","Black");
        print_r($array);
        echo "<br />";
        $array = array_flip($array);
        print_r($array);
       ?>
Copy after login

Run result:

Array ( [0] => red [1] => blue [2] => yellow [3] => Black ) 
Array ( [red] => 0 [blue] => 1 [yellow] => 2 [Black] => 3 )
Copy after login

Example 5: array_keys(), array_values() returns all keys and values ​​in the array:

	<?PHP
        $array = array("red","blue","yellow","Black");
        $result = array_keys($array);
        print_r($result);
        echo "<br />";
        $result = array_values($array);
        print_r($result);
       ?>
Copy after login

Run result:

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 ) 
Array ( [0] => red [1] => blue [2] => yellow [3] => Black )
Copy after login

Example 6: array_search() search value:

	<?PHP
        $array = array("red","blue","yellow","Black");
        $result = array_search("red",$array);
        if(($result === NULL)){
            echo "不存在数值red";
        }else{
            echo "存在数值 $result";
        }
       ?>
Copy after login

Result: Value 0 exists

The value returned by the function array_search() may be false or 0 or NULL, so be careful to use "==="

when making judgments

7. Sorting of arrays

Example 1: sort(), rsort()/asort(), arsort() to sort arrays:

<?PHP
    $array = array("b","c","d","a");
    sort($array);//从低到高排序
    print_r($array);
    echo "<br />";
    rsort($array);//逆向排序
    print_r($array);
?>
Copy after login

Result:

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

The sort() and rsort() functions sort the array from low to high, and the return result is a bool value;

The asort() and arsort() functions preserve the sorting of key values, and the key values ​​are not re-indexed after sorting.

Example 2: Disturbing the order of the array - shuffle() function:

<?PHP
    $array = array("a","b","c","d");
    shuffle($array);//从低到高排序
    print_r($array);
?>
Copy after login

结果为动态结果:

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

shuffle的结果有点随机的意味,每次刷新都不一样。

实例三:array_reverse()数组反向:

<?PHP
    $array = array("d","b","a","c");
    $array = array_reverse($array);//从低到高排序
    print_r($array);
?>
Copy after login

运行结果:

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

实例四:自然排序算法——natsort()和natcasesort();

<?PHP
    $array = array("sort2","Sort5","sort1","sort4");
    natsort($array);//从低到高排序
    print_r($array);
    echo "<br />";
    natcasesort($array);
    print_r($array);
?>
Copy after login

结果:

Array ( [1] => Sort5 [2] => sort1 [0] => sort2 [3] => sort4 ) 
Array ( [2] => sort1 [0] => sort2 [3] => sort4 [1] => Sort5 )
Copy after login

natsort()、natcasesort()对数组进行自然排序,就是使用数字的正常排序算法。natcasesort会忽略大小写。

实例五:对数组进行键值排序ksort():

<?PHP
    $array = array(1=>"sort2",4=>"Sort5",2=>"sort1",3=>"sort4");
    ksort($array);//从低到高排序
    print_r($array);
?>
Copy after login

结果:

Array ( [1] => sort2 [2] => sort1 [3] => sort4 [4] => Sort5 )
Copy after login

注意:ksort()函数重新建立了索引。

8. 数组的其他用法

   cout($array) --------统计数组的单元个数
  array_diff($array1,$array2)----------统计数组之间的不同点,返回第一个数组中有而第二个数组中没有的。
  array_diff_assoc($array1,$array2)---------同array_diff(),只是它对键值也比较
  array_diff_key($array1,$array2)------------比较键值
  array_product($array)-----------返回数组的所有数的乘积
  array_sum($array)--------------所有数值的和
  array_rand($array,$n)----------在$array数组中取出$n个数值,返回数组
  array_intersect($array1,$array2)----------------取得两个数组的交集
  array_intersect_assoc($array1,$array2)---------------在array_intersect 的基础上进行键值比较
  array_intersect_key($array1,$array2)-----------------比较两个数组键值的交集
Copy after login

总结

数组的使用在PHP中至关重要,由于PHP没有指针,所以数组承担了很大的数据操作任务。学好数组,才能把PHP应用的得心应手,这里所列均是常用的PHP数组相关的函数及用法,欢迎一起学习!

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/752575.htmlTechArticle对于Web编程来说,最重要的就是存取和读写数据了。存储方式可能有很多种,可以是字符串、数组、文件的形式等。数组,可以说是PHP的数...
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
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
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 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,

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

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