Home > Backend Development > PHP Tutorial > Summary of arrays in learning PHP [Experience], PHP array summary_PHP tutorial

Summary of arrays in learning PHP [Experience], PHP array summary_PHP tutorial

WBOY
Release: 2016-07-12 08:53:41
Original
931 people have browsed it

Learning PHP array summary [experience], PHP array summary

PHP has many functions about arrays to facilitate array operations.

Definition:

Each entity in the array contains two items: key and value, and its corresponding value can be obtained by querying the key. These keys can be numerical keys or associative keys. Numeric keys have no real connection to the value, they are just the position of the value in the array.

PHP provides many methods for traversing arrays, whether using associated keys or numerical keys. They all rely on a feature called array pointers.

Create array

PHP does not need to specify the size of the array when creating it. Because PHP is a loose language, there is no need to declare the array before using it. Although there are no restrictions, PHP provides formal and informal methods of array declaration.

References each element of a PHP array, indicated by a pair of square brackets. Arrays have no size limit, so you can create an array simply by establishing a reference, for example:

$state[0]= ‘111';

$state[1]= ‘222';
Copy after login

If the index value is a numeric index and is increasing, the index value can also be omitted when creating.

$state[] =‘111';

$state[] =‘222';
Copy after login

You can use array() to create an array, such as:

$state =array(‘111', ‘222');

$state =array(‘one'=>'111', ‘two'=>'222');
Copy after login

Use list() to extract an array, for example:

$state= array(‘one', ‘two', ‘three');

list($one,$two, $three) = $state;
Copy after login

The three values ​​in the array are assigned to $one, $two, $three respectively, and can be output directly.

Fill the array with a predefined range of values, for example:

$num= range(1, 6);

//类似于$num =array(1, 2, 3, 4, 5, 6);

可选择奇偶:$num =range(1, 6, 2);
Copy after login

//$num= array(1, 3, 5);

可选择字母:$ch =range(“A”, “F”);

//$ch= array(“A”, “B”, “C”, “D”, “E”, “F”);
Copy after login

Output array

The most common way to output the contents of an array is to iterate through each array key and output the corresponding value.

The foreach() function can easily traverse an array to get each value and key.

The print_r() function is very convenient for outputting the contents of an array to the screen. The prinf_r() function accepts a variable and sends its contents to standard output, returning TRUE on success, otherwise it returns FALSE.

Test array

Know whether a specific variable is an array through the is_array() function.

The is_array() function determines whether a variable is an array. If so, it returns TRUE, otherwise it returns FALSE. Even if the array contains only one value, it will be considered an array.

Add and remove array elements

PHP provides some functions for expanding and shrinking arrays, which facilitates the imitation of various queue implementations.

Add elements to the head of the array:

The array_unshift() function adds elements to the head of the array. All existing numeric keys are modified to reflect their new positions in the array, but associated keys are not affected.

$state= array(‘11', ‘22', ‘33');

array_unshift($state,‘00');

//$state= array(‘00', ‘11', ‘22', ‘33');
Copy after login

Add elements to the end of the array:

The array_push() function adds a value to the end of the array and returns the total number of elements in the array after adding the new value. At the same time, by passing this variable as an input parameter to this function, multiple variables (elements) are pushed into the array, in the form:

$state= array(‘1', ‘2');

array_push($state,‘3');

//$state= array(‘1', ‘2', ‘3');
Copy after login

Remove elements from the head of the array:

The array_shift() function removes and returns the first element found in the array. The result is that if numeric keys are used, all corresponding values ​​are shifted down, while arrays using associative keys are unaffected, in the form:

$state= array(‘1', ‘2');

array_shift($state);

//$state= array(‘2');
Copy after login

Delete elements from the end of the array:

The array_pop() function deletes and returns the last element of the array, its form is:

$state= array(‘1', ‘2');

array_pop($state);

//$state= array(‘1');
Copy after login

Positioning array elements

Search array:

The in_array() function searches for a specific value in the array. If the value is found, it returns TRUE, otherwise it returns FALSE. Its form is as follows:

$user= array(‘111', ‘222', ‘333');

$str= ‘111';

if(in_array($str,$user)){

echo‘yes';

}else{

echo ‘no';

}
Copy after login

The third parameter strict is optional, it forces in_array() to consider the type when searching.

Search associative array:

If a specified key is found in an array, the function array_key_exists() returns TRUE, otherwise it returns FALSE. Its form is as follows:

$arr= array('one'=>'1', 'two'=>'2', 'three'=>'3');

if(array_key_exists('two',$arr)){

echo'yes';

}else{

echo‘no';

}

Copy after login

Search associative array:

The array_search() function searches for a specified value in an array. If found, it returns the corresponding value, otherwise it returns FALSE. Its form is as follows:

$arr= array('one'=>'1', 'two'=>'2', 'three'=>'3');

if(array_search('1',$arr)){

echo'yes';

}else{

echo‘no';

}
Copy after login

Get array key:

The array_key() function returns an array containing all keys found in the searched array, in the following form:

$arr= array('one'=>'1', 'two'=>'2', 'three'=>'3');

$keys= array_keys($arr);

var_dump($keys);

//array(3) {[0]=> string(3) "one" [1]=> string(3) "two" [2]=>string(5) "three" }
Copy after login

Get array value:

The array_values() function returns all the values ​​in an array and automatically provides an array index for the returned array, which has the following form:

$arr= array('one'=>'1', 'two'=>'2', 'three'=>'3');

$values= array_values($arr);

var_dump($values);

//array(3) {[0]=> string(1) "1" [1]=> string(1) "2" [2]=>string(1) "3" }
Copy after login

Traverse the array

It is usually necessary to traverse the array and obtain each key or value (or obtain both the key and the value). PHP provides some functions to meet the needs. Many functions perform two tasks, not only obtain the key or value at the current pointer position, but also move the pointer to the next appropriate position.

Get the current array key:

The key() function returns the key at the current pointer position in the array, and its form is as follows:

$arr= array('one'=>'1', 'two'=>'2', 'three'=>'3');

$key= key($arr);

var_dump($key);

//string(3) "one"
Copy after login

Note: The pointer will not be moved each time key() is called.

获取当前数组值:

current()函数返回数组中当前指针所在位置的数组值。其形式如下:

$arr= array('one'=>'1', 'two'=>'2', 'three'=>'3');

$value= current($arr);

var_dump($value);

//string(1)“1”
Copy after login

获取当前数组键和值:

each()函数返回数组的当前键/值对,并将指针推进一个位置,其形式如下:

$arr =array('one'=>'1', 'two'=>'2', 'three'=>'3');

var_dump(each($arr));

//array(4) {[1]=> string(1) "1" ["value"]=> string(1)"1" [0]=> string(3) "one" ["key"]=>string(3) "one" }
Copy after login

返回的数组包含4个键,键0和key键包含键名,而键1和value包含相应的数据。如果执行each()前指针位于数组末尾,则返回FALSE。

移动数组指针:

1) 将指针移动到下一个数组位置

next()函数返回紧接着放在当前数组指针下一个位置的数组值,如果指针本来就位于数组的最后一个位置,则返回FALSE

$arr= array('one'=>'1', 'two'=>'2', 'three'=>'3');

echo next($arr); //输出2

echo next($arr); //输出3
Copy after login

2) 将指针移动到前一个数组位置

prev()函数返回位于当前指针前一个位置的数组值,如果指针本来就位于数组的第一个位置,则返回FALSE

3) 将指针移动到第一个数组位置

reset()函数用于将数组指针设置回数组的开始位置,如果需要在脚本中多次查看或处理一个数组,经常使用这个函数,另外这个函数还经常在排序结束时使用。

4) 将指针移动到最后一个数组位置

end()函数将指针移动到数组的最后一个位置,并返回最后一个元素。

向函数传递数组值:

array_walk()函数将数组中的各个元素传递到用户自定义函数。如果需要对各个数组元素完成某个特定动作,这个函数将起作用。其形式如下:

functiontest($value ,$key){

echo$value.' '.$key."
";

}

$arr= array('one'=>'1', 'two'=>'2', 'three'=>'3');

array_walk($arr,'test');

//1 one

//2 two

//3 three
Copy after login

如果使用多维数组,PHP5中引入的array_walk_recursive()函数可以递归地对数组中的每一个元素应用一个用户定义函数。

确定数组大小和元素唯一性

确定数组的大小:

count()函数返回数组中值的总数

如果启动了可选的mode参数(设置为1),数组将进行递归计数统计元素。count(array(), 1);

注意:sizeof()函数是count()的别名。功能一致。

统计数组元素出现的频率:

array_count_values()函数返回一个包含关联键/值对的数组,其形式如下:

$arr= array('A', 'B', 'C', 'A');

$res= array_count_values($arr);

print_r($res);

//Array( [A] => 2 [B] => 1 [C] => 1 )
Copy after login

值表示出现的频率。

确定唯一的数组元素:

array_unique()函数会删除数组中所有重复的值,返回一个由唯一值组成的数组,其形式如下:

$arr= array('A', 'B', 'C', 'A');

$res= array_unique($arr);

print_r($res);

//Array( [0] => A [1] => B [2] => C )
Copy after login

可选参数sort_flags(PHP5.2.9中新增)可以确定如何对数组键排序。默认地,值会被作为字符串排序,不过也可以按数值对值排序(SORT_NUMERIC),或使用PHP默认的排序方法(SORT_REGULAR),还可以根据本地化环境排序(SORT_LOCALE_STRING)。

数组排序

逆置数组元素排序:

array_reverse()函数将数组中元素的顺序逆置,其形式如下:

$arr= array('A', 'B', 'C');

$res= array_reverse($arr);

print_r($res);

//Array( [0] => C [1] => B [2] => A )
Copy after login

如果可选参数preserve_keys设置为TRUE,则保持键映射,否则重新摆放后的各个值将对应于先前该位置上的相应键。

$arr= array('A', 'B', 'C');

$res= array_reverse($arr, true);

print_r($res);

//Array( [2] => C [1] => B [0] => A )
Copy after login

置换数组键和值:

array_flip()函数将置换数组中键及其相应值的角色,其形式如下:

$arr= array('A', 'B', 'C');

$res= array_flip($arr);

print_r($res);

//Array( [A] => 0 [B] => 1 [C] => 2 )
Copy after login

数组排序:

sort()函数对数组进行排序,各元素按值由低到高的顺序排列,其形式如下:

sort()函数不返回排序后的数组,相反它只是“就地”对数组排序,不论结果如何都不返回任何值。sort_flags参数可选,将根据这个参数指定的值修改该函数的默认行为。

1) SORT_NUMERIC,按数值排序。对整数和浮点数排序很有用。

2) SORT_REGULAR,按照相应的ASCII值对元素排序。

3) SORT_STRING,按接近于人所认知的正确顺序对元素排序。

要保持初始键/值对应条件下的数组排序需要用到asort()函数。

assort()函数与sort()函数相同,以升序对数组排序,只不过它将保持键/值的关联,其形式如下:

$arr= array('C', 'B', 'A');

$res= $arr;

print_r($arr);

sort($arr);

print_r($arr);

asort($res);

print_r($res);

//Array ( [0]=> C [1] => B [2] => A ) Array ( [0] => A [1] => B [2] => C )Array ( [2] => A [1] => B [0] => C )
Copy after login

以逆序对数组排序

rsort()函数与sort()函数相同,只不过它以相反的顺序(降序)对数组元素排序。

如果使用可选的sort_flags参数,具体的排序行为将由这个值确定。

保持键/值对的条件下以逆序对数组排序

与asort()一样,arsort()函数会保持键/值的关联,但是它以逆序对数组up

$arr= array('C', 'B', 'A', 'D');

arsort($arr);

print_r($arr);

//Array( [3] => D [0] => C [1] => B [2] => A )
Copy after login

如果使用可选的sort_flags参数,具体的排序行为将由这个值确定。

数组自然排序

natsort()函数提供了一种相当于人们平常使用的排序机制。

典型算法排序如下:

p1.jpg,p10.jpg, p2.jpg, p20.jpg

使用natsort()函数如下:

p1.jpg,p2.jpg, p10.jpg, p20.jpg

不区分大小写的自然排序

如:

Picture1.jpg,PICTURE10.jpg, picture2.jpg, picture20.jpg

按键值对数组排序

ksort()函数按键对数组排序,如果成功则返回TRUE,失败将返回FALSE

以逆序对数组键排序

krsort()函数的操作与ksort()相同,也按键排序,将以逆序排序。

根据用户自定义规则排序

usort()函数提供了另一种排序方法,可以使用在该函数中指定的用户自定义比较算法对数组排序。如果需要以某种方法对数据排序,而PHP的任何内置排序函数没有提供相应支持,就需要该函数。

数组合并、拆分、接合和分解

合并数组

array_merge()函数将数组合并到一起,返回一个联合的数组。所得到的数组以第一个输入数组参数开始,按后面数组参数出现的顺序依次追加。其形式如下:

$arr= array('C', 'B', 'A', 'D');

$arr1= array('1', '2', '3', '4');

$arr2= array_merge($arr, $arr1);

print_r($arr2);

//Array( [0] => C [1] => B [2] => A [3] => D [4] => 1 [5] => 2 [6]=> 3 [7] => 4 )
Copy after login

递归追加数组

array_merge_recursive()函数与array_merge()相同,可以将两个或多个数组合并到一起,形成一个联合的数组。两者之间的区别在于,当某个输入数组中的某个键已经存在于结果数组中时该函数会采取不同的处理方法。array_merge()会覆盖前面存在的键/值对,将其替换为当前输入数组中的键/值对,而array_merge_recursive()将两个值合并在一起,形成一个新的数组并以原有的键作为数组名。其形式为:

$arr= array('one'=>'C', 'one'=>'B');

$arr1= array('three'=>'1', 'one'=>'2');

$arr2= array_merge_recursive($arr, $arr1);

print_r($arr2);

//Array( [one] => Array ( [0] => B [1] => 2 ) [three] => 1 )
Copy after login

合并两个数组

array_combine()函数会生成一个新数组,这个数组由一组提交的键和对应的值组成,其形式为:

$arr= array('A', 'B');

$arr1= array('1', '2');

$arr2= array_combine($arr, $arr1);

print_r($arr2);

//Array( [A] => 1 [B] => 2 )
Copy after login

拆分数组

array_slice()函数将返回数组中的一部分,从键offset开始,到offset+length位置结束。

offset为正值时,拆分将从距数组开头的offset位置开始;如果offset为负值,则拆分从距数组末尾的offset位置开始。如果省略了可选参数length,则拆分将从offset开始,一直到数组的最后一个元素。如果给出了length且为正数,则会在距数组开头的offset+length位置结束。相反,如果给出了length且为负数,则在距数组开头的count(array) - |length|位置结束。其形式如下:

$arr= array('A', 'B', 'C', 'D');

$arr1= array_slice($arr, 2, 1);

print_r($arr1);

//Array( [0] => C )
Copy after login

求数组的交集

array_intersect()函数返回一个保留了键的数组,这个数组只由第一个数组中出现的且在其他每个输入数组中都出现的值组成。其形式如下:

$arr= array('A', 'B', 'C', 'D');

$arr1= array('A', 'B', 'E');

$arr2= array('A', 'F', 'D');

$arr3= array_intersect($arr, $arr1, $arr2);

print_r($arr3);

//Array( [0] => A )
Copy after login

注意:只有在两个元素有相同的数据类型时,array_intersect()才会认为它们相等。

求关联数组的交集

array_intersect_assoc()与array_intersect()基本相同,只不过它在比较中还考虑了数组的键。因此,只有在第一个数组中出现,且在所有其他输入数组中也出现的键/值对才被返回到结果数组中。其形式如下:

$arr= array('a'=>'A', 'b'=>'B', 'c'=>'C', 'd'=>'D');

$arr1= array('a'=>'A', 'c'=>'B', 'E');

$arr2= array('a'=>'A', 'b'=>'F', 'd'=>'B');

$arr3= array_intersect_assoc($arr, $arr1, $arr2);

print_r($arr3);

//Array( [a] => A )
Copy after login

求关联数组的差集

函数array_diff_assoc()与array_diff()基本相同,只是它在比较时还考虑了数组的键,因此,只在第一个数组中出现而不在其他输入数组中出现的键/值对才会被返回到结果数组中。其形式如下:

$arr= array('a'=>'A', 'b'=>'B', 'c'=>'C', 'd'=>'D');

$arr1= array('a'=>'A', 'b'=>'B', 'e'=>'E');

$arr3= array_diff_assoc($arr, $arr1);

print_r($arr3);

//Array( [c] => C [d] => D )
Copy after login

其他有用的数组函数

返回一组随机的键

array_rand()函数将返回数组中的一个或多个键。其形式为:

$arr= array('a'=>'A', 'b'=>'B', 'c'=>'C', 'd'=>'D');

$arr1= array_rand($arr, 2);

print_r($arr1);

//Array( [0] => b [1] => d )
Copy after login

随机洗牌数组元素

shuffle()函数随机地对数组元素重新排序。

对数组中的值求和

array_sum()函数将数组内的所有值加在一起,返回最终的和,其形式如下:

$arr= array('A', 32, 12, 'B');

$count= array_sum($arr);

print_r($count);

//44
Copy after login

如果数组中包含其他数据类型(例如字符串),这些值将被忽略。

划分数组

array_chunk()函数将数组分解为一个多维数组,这个多维数组由多个包含size个元素的数组所组成。其形式如下:

$arr= array('A', 'B', 'C', 'D');

$arr1= array_chunk($arr, 2);

print_r($arr1);

//Array( [0] => Array ( [0] => A [1] => B ) [1] => Array ( [0] => C [1]=> D ) )
Copy after login

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1123803.htmlTechArticle学习PHP的数组总结【经验】,php数组总结 PHP有很多关于数组的函数,方便数组操作。 定义: 数组每个实体包含两个项:key和value,可以通...
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