Xi. Array 1, what is an array?
An array is a special variable that can hold more than one value at a time.
Arrays can store many values in a single variable name, and you can access a value by referencing the label.
2, three types of arrays
- indexed Array -an array with a numeric index
- Associative array -an array with the specified key
- multidimensional Arrays -an array that contains one or more arrays
3. Create an array (1) with arrays (), create an indexed array
$its=array("Google","Apple","Microsoft");print_r($its);
Or
$its[0]="Google";$its[1]="Apple";$its[2]="Microsoft";print_r($its);
Operation Result:Array ( [0] => Google [1] => Apple [2] => Microsoft )
(2), creating associative arrays
$age=array("Peter"=>"20","Bill"=>"19","Ken"=>"21");print_r($age);
Or
$age["Peter"]="20";$age[‘Bill‘]="19";$age["Ken"]="21";print_r($age);
Operation Result:Array ( [Peter] => 20 [Bill] => 19 [Ken] => 21 )
4. Get the array length with count ()
$its=array("Google","Apple","Microsoft");$age=array("Peter"=>"20","Bill"=>"19","Ken"=>"21");echo count($its)."<br />";echo count($age);
Operation Result:
3
3
5. Iterate through the array (1) with for and foreach, and use for to iterate over the indexed array
$its=array("Google","Apple","Microsoft");for($i=0;$i<count($its);$i++){ echo$its[$i]."<br />";}
Operation Result:
Google
Apple
Microsoft
(2), using foreach to iterate through associative arrays
$age=array("Peter"=>"20","Bill"=>"19","Ken"=>"21");foreach($ageas$value){echo$value."<>";}
Operation Result:
20
19
21
6. Array sorting
Sort ()-sorts an array in ascending order
Rsort ()-sorts the array in descending order
Asort ()-sorts associative arrays in ascending order based on values
Ksort ()-Sorts the associative array in ascending order, based on the key
Arsort ()-sorts associative arrays in descending order by value
Krsort ()-Sorts the associative array in descending order, based on the key
How do you remember them?
R--reduce, reducing
A--value, value (do not know is not, for the record)
K--key, key
$age =array ( "Peter" => ", " Bill " => ", " Ken " = ); foreach ( $age as $value ) {echo $value . " <br/> ";} Arsort ( $age ); foreach ( $age as $value ) {echo $value . " <br/> ";}
Operation Result:
20
19
21
21
20
19
Copyright NOTICE: This article for Lshare original article, need to reprint please contact me, have questions welcome comments or private messages.
PHP basic Syntax (iv)