search
HomeBackend DevelopmentPHP TutorialImportant: Summary of various operations and functions of PHP arrays_PHP Tutorial

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")    //最后一句没有标点
    );
?>

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);
?>

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? ) 
)

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);
?>

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 )

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);
?>

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 "
"; ?>

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
)

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 />";
	}
?>

Run result:

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

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>";
       ?>

for loop traversal

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

Run result:

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

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 />";
?>

Run result:

0220
200
0
220

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 />";
    }
?>

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

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);
      ?>

Run result:

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

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);
    ?>

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 )

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);
    ?>

Run result:

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

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);
    ?>

Run result:

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

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命令可以删除数组";
        }
    ?>

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命令不能删除整个数组

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

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);
    ?>

Run result:

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

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 "
"; ?>

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

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 "数组中存在";
        }
    ?>   

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;
    ?>

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>";
?>

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);
       ?>

Run result:

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

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);
       ?>

Run result:

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

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";
        }
       ?>

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);
?>

Result:

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

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);
?>

结果为动态结果:

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

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

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

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

运行结果:

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

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

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

结果:

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

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

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

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

结果:

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

注意: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)-----------------比较两个数组键值的交集

总结

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/752575.htmlTechArticle对于Web编程来说,最重要的就是存取和读写数据了。存储方式可能有很多种,可以是字符串、数组、文件的形式等。数组,可以说是PHP的数...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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 and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software