Home >Backend Development >PHP Tutorial >Some practical knowledge in php arrays

Some practical knowledge in php arrays

零下一度
零下一度Original
2017-06-27 11:05:371083browse

PHP Array

Array is a special variable that can save more than one at the same time value.

***Keywords: Array basics, array traversal, super global array, array function, array function.

Let’s share with you the basic knowledge of arrays in PHP. I hope it will be helpful to your learning of PHP~

Classification of PHP arrays


According to different subscripts, PHP arrays are divided into associative arrays and index arrays;
Index array: the subscript starts from 0 and increases in sequence
Associative array: the subscript is String format, each subscript string is associated with the value of the array one-to-one (similar to the key-value pair of an object)

Code demonstration:

1 $arr1 = array(1,2,3,4,5,6,7);//索引数组2 var_dump($arr1);3    4 $arr2 = array("one"=>1,"two"=>2,"three"=>3);//关联数组5 var_dump($arr2);6    7 $arr3 = array(1,"one"=>2,3,5=>4,5,6,"10.0"=>7,"08"=>8,"08"=>10,"hahah"=>9);8 var_dump($arr3);

About associative arrays and index arrays


1. In an array, an index array and an associative array can exist at the same time.
array(1,2,3,"one"=>4);

2. In the array, all The index array, if not specified, will remove the associated items and grow by default (that is, the associated array does not occupy the index position);
array(1,2,"one"=>3, 4,5);//Index of 1,2,4,5--->0/1/2/3

3. If, The key of the associative array is a pure decimal integer string.
will convert this number into the index value of the index array; (formats such as "10.0"/"08" are still associative arrays. Not converted to index)
array(1,2,"one"=>3,"9"=>4,"010"=>5);//1,2 , index of 4 --->0/1/9

4. If, manually specify the key of the associated array, the subscript of the index array, if If it repeats the previous key or subscript, the later specified value will overwrite the previous value;
array(1,"one"=>2,0=>5," one"=>6);--->Print array, 0=>5, "one"=>6

5, if If you manually specify the index array subscript, subsequent self-increasing subscripts will increase sequentially according to the maximum value of the previous subscript.
array(1,2,7=>3,4);--->The subscript of 1,2,3,4--->0/1/7/ 8

How to declare array


1. Direct assignment statement
$arr[] = 1;
$arr[] = 1;
$arr[] = 1;
$arr[] = 1;
$arr[] = 1;
var_dump($arr);

2, [] literal declaration (can be used after PHP5.4 version)
$arr ​​= [1, 2,3,4,"one"=>5,6];
var_dump($arr);

3. Array() statement No new keyword
$arr ​​= array(1,2,3,4,5);
var_dump($arr);

数组元素的读取


PHP中,数组支持[]和{}读取下标。


多维数组

①数组的一个值,依然是一个数组,我们称这种数组为多维数组;
②多维数组,不要求所有的项都是数组,可以是数组与普通值的混合;
③多维数组,也不要求每个子数组的个数限制,可以是任意的长度。

使用多维数组,一定要注意,数组中分隔用逗号!
原则上,多维数组一般不超过3层使用!

 

三维数组代码演示如下:

 1 $H51701 = array( 2 "group1"=>array( 3 array("name"=>"张三","age"=>14,"sex"=>"男"), 4 array("name"=>"李四","age"=>15,"sex"=>"男"), 5 array("name"=>"王二","age"=>13,"sex"=>"男") 6 ), 7 "group2"=>array( 8 array("name"=>"张三","age"=>15,"sex"=>"男"), 9 array("name"=>"李四","age"=>15,"sex"=>"男"),10 array("name"=>"王二","age"=>14,"sex"=>"男")11 ),12 "group3"=>array(13 array("name"=>"张三","age"=>14,"sex"=>"男"),14 array("name"=>"李四","age"=>18,"sex"=>"男"),15 array("name"=>"王二","age"=>24,"sex"=>"男")16 ),17 );18 var_dump($H51701);
##1. Basic part of PHP array
二、数组遍历


1、使用for循环遍历数组

count($arr);用于统计数组元素的个数

for循环只能用于遍历,纯索引数组!
如果存在关联数组,count统计时会统计两种数组的总个数,使用for循环遍历混合数组,导致数组越界!

代码如下:

1 $arr = array(1,2,3,"one"=>4,5,6,7);2 $num = count($arr);3 echo"数组元素的个数{$num}<br/>";4 for($i=0;$i<$num;$i++){5 echo "{$i}==>{$arr[$i]}<br/>";6 }

 

2、forEach循环遍历数组
foreach可以遍历任何类型的数组!

代码如下:

1 $arr = array(1,2,3,"one"=>4,5,6,7);2 foreach($arr as $key=>$item){3 echo "{$key}==>{$item}<br/>";4 }

 

下面我们来做一个数组遍历的小练习~看代码~

 1 $arr = array( 2 "group1"=>array( 3 array("name"=>"张三","age"=>14,"sex"=>"男"), 4 array("name"=>"李四","age"=>12,"sex"=>"男"), 5 array("name"=>"王二","age"=>18,"sex"=>"男") 6 ), 7 "group2"=>array( 8 array("name"=>"张三","age"=>14,"sex"=>"男"), 9 array("name"=>"李四","age"=>16,"sex"=>"男"),10 array("name"=>"王二","age"=>19,"sex"=>"男")11 ),12 "group3"=>array(13 array("name"=>"张三","age"=>14,"sex"=>"男"),14 array("name"=>"李四","age"=>12,"sex"=>"男"),15 array("name"=>"王二","age"=>13,"sex"=>"男")16 ),17 );18 19 foreach($arr as $key=>$value){20 echo "{$key}<br/>"; 
21 foreach($value as $key1=>$value1){22 echo "第".($key1+1)."个同学<br/>";23 foreach($value1 as $key2=>$value2){24 echo "{$key2}==>{$value2}<br/>";25 }26 echo"<br/>";27 }28 echo"----------------------<br/>";29 }

 

3、使用list(),each(),while()遍历数组
list():用于将数组的每一个值,赋值给list函数的每一个参数。(list函数的参数,必须<=数组的元素个数);
eg:list($a,$b,$c) = [1,2,3]; --->$a=1; $b=2; $c=3;

注意
①list()在解析数组时,只解析索引数组;
②list可以通过空参数,选择性的解析数组的值;
list($a,,$b)=[1,2,3];-->$a=1;$b=3;

each():用于返回数组当前指针所在位的键值对!并将指针后移一位;
返回值:如果指针有下一位,返回一个数组。包含一个索引数组(0-键,1-值)和一个关联数组("key"-键,"value"-值);
如果指针没有下一位,返回false。

4、使用list()/each()/while()配合遍历数组※※※

1 while(list($key,$value) = each($arr)){2 echo "{$key}-->{$value}<br>";3 }4 reset($arr);

!!!数组使用each()遍历完一遍后,指针使用处于最后一位的下一位,即再用each(),始终返回false;
如果还需使用,需用reset($arr);函数,重置数组指针。

$arr = [1,2,3,4];
list($a,$b,$c,$d) = $arr;
echo "a-->{$a}
";

echo "b-->{$b}
";

echo "c-->{$c}
";

echo "d-->{$d}
";

while($a = each($arr))

①each($arr)返回数组或false;
②把数组或false赋值给$a;
③while判断$a如果是数组,继续执行下一位;
如果$a是false,终止循环。

 1 while($a = each($arr)){ 2 echo "{$a[0]}-->{$a[1]}<br>"; 3 echo "{$a['key']}-->{$a['value']}<br>"; 4 } 5  6 while(true){ 7 $a = each($arr); 8 if($a){ 9 echo "{$a[0]}-->{$a[1]}<br>";10 echo "{$a['key']}-->{$a['value']}<br>";11 }else{12 break;13 }14 }15 16 while(list($key,$value) = each($arr)){17 echo "{$key}-->{$value}<br>";18 } 
19 reset($arr);

 

5、使用数组指针遍历数组

①next:将数组指针,后移一位,并返回后一位的值,没有返回false
②prev:将数组指针,前移一位,并返回前一位的值,没有返回false
③end:将数组指针,移至最后一位,返回最后一位的值,空数组返回false
④reset:将数组指针,恢复到第一位,并返回第一位的值,空数组返回false
⑤key:返回当前指针所在位的键;
⑥current:返回当前指针所在位的键;

 1 $arr = [1,2,3,4,"one"=>5]; 2 while(true){ 3 echo key($arr); 4 echo "--"; 5 echo current($arr); 6 echo "<br>"; 7 if(!next($arr)){ 8 break; 9 }10 }11 reset($arr);12 do{13 echo key($arr);14 echo "--";15 echo current($arr);16 echo "<br>";17 }while(next($arr));18 reset($arr);

 

三、超全局数组


超全局数组,超全局变量,预定义数组,预定义变量——说的都是它。

PHP给我们提供了一组包含强大功能的超全局数组,可以在任何地方,任何作用域不需声明,直接使用!不受任何作用域限制。

PHP超全局数组

       1、服务器变量: $_SERVER
  2、环境变量:$_ENV
  3、HTTP GET变量:$_GET
  4、HHTP POST变量:$_POST
  5、request变量:$_REQUEST
  6、HTTP文件上传变量:$_FILES
  7、HTTP Cookies:$_COOKIE
  8、Session变量:$_SESSION
  9、Global变量:$GLOBALS

 

1、服务器变量: $_SERVER
var_dump($_SERVER);
echo ($_SERVER{'HTTP_USER_AGENT'});

2、环境变量:$_ENV
将系统环境变量,转变为PHP中的数组,就是$_ENV;

PHP默认是关闭此全局数组的。如果需要使用,
需修改php.ini文件中的variables_order = "GPSC",
改为variables_order = "EGPSC";

但是,修改后会有系统性能损失,港方并不推荐使用。
可以使用getenv()函数取代全局变量,取出每个系统环境变量的值。

phpinof();函数,包含了有关PHP的各种信息,其实environment板块就是系统环境的变量,可以使用getevn()函数取出其中的值;

3、HTTP GET变量:$_GET
获取前台通过get方式提交的数据

1 if(isset($_GET["sybmit"]&&isset($_GET["pwd"]))){2 if($_GET["username"]=="111"&&$_GET["pwd"]=="111"){3 echo "Get登录成功!";4 }else{5 echo "Get登录失败!";6 }7 }

 

4、HHTP POST变量:$_POST
获取前台通过post方式提交的数据

1 if(isset($_POST["sybmit"])){2 if($_POST["username"]=="111"&&$_POST["pwd"]=="111"){3 echo "POST登录成功!";4 }else{5 echo "POST登录失败!";6 }7 }

5. request variable: $_REQUEST
Contains an array of $_GET, $_POST and $_COOKIE
Because Request contains both get and post, which may cause key conflicts between get and post, and the frequency is not high. Therefore, request is not used.
var_dump($_REQUEST);

6. HTTP file upload variable: $_FILES
Upload via HTTP POST An array of items to the current script.
var_dump($_FILES);

7. HTTP Cookies:$_COOKIE
Get the cookie information in the page
1 setcookie("cookie","haha");

##2 $_COOKIE["hehe"] = "hehe";

##3 var_dump($_COOKIE);

8. Session variable: $_SESSION
Get the information saved in Session.
session_start();
$_SESSION["haha"] = "haha";
var_dump($_SESSION);* /

9. Global variable: $GLOBALS
$GLOBALS contains the above 8 global arrays, which can be obtained through $GLOBALS["_SERVER"] $_SERVER
can also be added by appending subscripts to the $GLOBALS array. Create global variables that can be accessed freely inside and outside the function: $GLOBALS["name"] = "zhangsan";
var_dump($GLOBALS["_SERVER"]);

 

1、返回数组所有的值,返回数组
var_dump(array_values($arr));

2、返回数组所有的键,返回数组
var_dump(array_keys($arr));

3、检测数组中是否包含某个值。返回真、假
参数:需要查询的值,数组,true(===)/false(===) 默认
var_dump(in_array("8",$arr,true));

4、交换数组中的键和值,返回新数组
var_dump(array_flip("8",$arr));

5、反转数组,返回新数组
参数:需要反转的数组
true:保留原有索引数组的下标与值的匹配。
false:只反转值,键不反转,默认
无论true/false,都不会影响关联数组,关联数组键,值永远是一对。
var_dump(array_reverse($arr,true));

6、统计数组元素个数
count($arr);

7、统计数组中,所有值出现的次数,返回一个新数组
新数组格式:键-->原数组的值(去重后的值)
        值-->原数组对应的值出现的次数。
var_dump(array_count_values($arr));

8、移出数组中重复的值!
var_dump(array_unique($arr));

9、过滤数组中的每一个值:
①不传回调函数:过滤掉所有空值(0/""/null/false/"0"/[])
②传回调函数:需要给回调函数传递一个参数,判断参数是否符合要求,如果符合,return true;否则,return false。

1 var_dump(array_filter($arr,function($num){2 if($num>4){3 return true;4 }else{5 return false;6 }7 }));


通过回调函数,对数组的每一个值,进行处理操作。(直接修改原数组,并返回bool类型的是否成功)
执行时,会给回调函数传递两个参数,分别是数组的value,key,然后可以在毁掉函数中,对值和键进行处理。
但是,牵扯到修改值的时候,必须要传递地址&!!!!
$fruits = array("d" => "lemon","a" => "orange","b" => "banana","c" => "apple");

1 var_dump(array_walk($fruits,function(&$item,$key){2 echo "{$key}-->{$item}<br>";3 $item .= $key;4 }));5 var_dump($fruits);

 

将数组的每个值交由回调函数进行映射处理
array_map():第一个参数,是一个回调函数。第二个参数起,是>=1个数组。
有几个数组,可以给回调函数传几个参数,,表示每个数组的一个value;
可以对value进行处理,处理完以后通过return返回,那么新数组的对应的值就是你return回去的值。

【array_map与array_walk的异同】
相同点都能遍历数组,通过回调函数,重新处理数组的每一个值;
不同点
①walk只能传一个数组,回调函数接收这个数组的值和键;
map可以传多个数组,回调函数接收每个数组的值;
②walk直接修改原数组,而map不修改原数组,将新数组返回;
③walk给回调函数传递一个其余参数,map只能传数组的值;
④处理方式上,walk如果需要改掉原数组的值,需在回调函数中传递地址,直接修改变量的值;
而map,是通过将新的值,用return返回,即可修改新数组的值。
$a = [1,2,3,4,5];
$b = [1,2,3,4,5];

1 var_dump(array_walk($fruits,function(&$item,$key){2 echo "{$key}-->{$item}<br>";3 $item .= $key;4 }));5 var_dump($fruits);

 

4. Array function
五、数组函数

sort -- Sort the array (ascending order)

var_dump(sort($arr));


rsort-- Sort the array in reverse order (descending order)


usort--Use user-defined The defined comparison function sorts the values ​​in the array


asort--sorts the array and maintains the index relationship (associative array sorting)


arsort--Reverse sort the array and maintain the index relationship


##uasort --User-defined comparison function sorts the array and maintains index association


ksort--Sorts the array by key name


krsort--Reverse sort the array according to the key name


uksort--Use a user-defined comparison function to sort the key names in the array


natsort--Use the "natural sorting" algorithm to sort the key names in the array. Array sorting


natcasesort--Use the "natural sorting" algorithm to sort the array in case-insensitive letters


array_multisort -- Sort multiple arrays or multidimensional arrays
The first parameter: the first array, required
The second parameter: SORT_DESC;SORT_ASC (ascending and descending order);
The third parameter: SORT_STRING/SORT_NUMERIC (sort by string or number)
Then there are multiple arrays
Sorting rules: Sort the first array first, and the subsequent arrays will be sorted column by column according to the corresponding relationship with the first array;

If multiple arrays are sorted, the lengths of the sorted arrays must be equal, otherwise a warning will be reported;

array_slice($array, $offset)
First parameter: Array, required;
Second parameter: Starting from which number to cut, a negative number means counting from right to left (according to the order of the array ps: including Associative array, not subscript)
The third parameter: the intercepted length, optional, intercepted to the end by default
The fourth parameter: bool type Parameter, default is false, index is reordered, true keeps index association
$arr1 = array_slice($arr, 2,5,TRUE);


array_splice($offset)
Return value: array (the deleted part)
Parameters:
1, The address of the array will modify the original array
2. Delete from the starting position
3. The length of the deletion, if not filled in, will default to the end
4. If not filled in, the default is to delete. If filled in, replace the deleted part with the filled part;
$arr1 = array_splice($arr, 2,5,[1,2 ,3,4]);


array_combine($keys, $values);Create an array and use the value of an array as the key name. The value of another array as the value;
array_combine($keys'array as key', $values'array as value');
Two arrays The lengths must be consistent, otherwise a warning will be reported


array_merge($array1);Merge one or more arrays
Merge multiple arrays, and splice the following array into the previous array The following
If there are multiple associated keys with the same name in multiple arrays, the following ones will overwrite the previous


array_intersect( $array1, $array2);Intersection of two arrays
Intersection of multiple arrays, the result will retain the key-value association matching of the first array


array_diff($array1, $array2);Get the difference set of multiple arrays;
Take out multiple arrays, in the first array Values ​​that are included but not included in other arrays retain the key-value association of the first array;


##array_pop();

Delete the last value of the array; return the deleted value;


array_push($var);
Insert an or at the end of the array Multiple values; return the number of elements after processing

##array_shift();
Delete the first value of the array; return the deleted value ;

array_unshift($var);
Insert one or more values ​​at the beginning of the array; return the number of elements after processing


array_rand($input);Randomly select one to multiple key names in the array! The second parameter is empty, which means to draw one, and passing in the number n means to draw n


shuffle();Shuffle and reorder the function

Okay~~~Today’s content is shared here first. I am a little girl and a newbie. I also ask all garden friends to give me some advice. If you like it, please give it a like~Thank you for your support!

The above is the detailed content of Some practical knowledge in php arrays. For more information, please follow other related articles on the PHP Chinese website!

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