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~
##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给我们提供了一组包含强大功能的超全局数组,可以在任何地方,任何作用域不需声明,直接使用!不受任何作用域限制。
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"]);
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
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!