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

WBOY
Release: 2016-07-13 10:32:59
Original
679 people have browsed it

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的数...
Related labels:
source: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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template