1. An array can store multiple values in a single variable
<?php header("Content-type: text/html; charset=utf-8");//设置编码 $arr = array('one','two','three','four','five'); ?>
2. What is an array
An array is a special variable that can store multiple values in a single variable
Arrays can store multiple values in a single variable, and the values can be accessed based on keys
3. How to create an array in php
array () Function is used to create arrays
4. There are 3 arrays in php
(1). Arrays with numeric ID keys----numeric arrays
(2). Array with specified keys, each key is associated with a value -------Associative array
(3). Array containing one or more arrays---- ----Multidimensional array
Numeric array
<?php $cars=array("Volvo","BMW","Toyota"); //创建一个名为 $cars 的数值数组,并给数组分配三个元素 echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; ?>
Associative array
Associative array is an array using the specified key that you assign to the array
<?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); echo "Peter is " . $age['Peter'] . " years old."; ?>
Traverse the association Array
<?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); //是使用foreach 遍历关联数组 foreach($age as $x=>$x_value){ echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; } ?>
Traverse and print all values in the associative array
Multidimensional array
<?php $arr = array( array( "www.taobao.com", "www.baidu.com" ), array( "www.php.cn", "www.tianmao.com" ) ); print('<pre>'); print_r($arr); print('</pre>'); ?>
Get the array length----------count() function
In the following case, get the length of an array
<?php $arr = array(1,2,3,4,5,6,7,8,9); echo count($arr); ?>
Array sorting
Array sorting, There are functions for sorting arrays in php
1.sort() - Sort the array in ascending order
2.rsort() - Sort the array in descending order
3 .asort() - Sort the array in ascending order based on the value of the associative array
4.ksort() - Sort the array in ascending order based on the keys of the associative array
5.arsort() - Sort the array in descending order according to the value of the associative array
6.krsort() - Sort the array in descending order according to the key of the associative array
sort()
<?php //升序 $arr = array(1,15,6,8,1,28,35,26,7); sort($arr); echo "<pre>"; print_r($arr); echo "</pre>"; ?>
##rsort()
<?php //降序 $arr1 = array(1,15,6,8,28,35,26,7); rsort($arr1); echo "<pre>"; print_r($arr1); echo "</pre>"; ?>
##asort()<?php
//asort
$arr = array('a','b','c');
asort($arr);
echo "<pre>";
print_r($arr);
echo "</pre>";
?>
arsort()<?php
//arsort
$arr = array('a','b','c');
arsort($arr);
echo "<pre>";
print_r($arr);
echo "</pre>";
?>
ksort()<?php
//ksort
$arr = array('a'=>10,'b'=>5,'c'=>20);
ksort($arr);
echo "<pre>";
print_r($arr);
echo "</pre>";
?>
krsort()<?php
//krsort
$arr = array('a'=>10,'b'=>5,'c'=>20);
krsort($arr);
echo "<pre>";
print_r($arr);
echo "</pre>";
?>