The Declaration and traversal of an array of PHP learning notes

Source: Internet
Author: User
Tags foreach arrays numeric mixed prev

The declaration of an array

1, direct assignment way to declare an array

$ array variable name [index value] = data content//The index value (subscript) can be a string or a number

But sometimes, we can also assign values directly to the array, do not fill in the "index value", that at this time, the array of subscript will automatically start with the number 0 increase.

$ array variable name [] = data content//The index value (subscript) can be a string or a number

2. Use the array () language structure to create a new array

In practice, we can use the array () language structure to create a new array and initialize the array.

$ array variable name =array (key1 => value1, Key2 => value2, ..., Keyn =>);

Of course, like the above we are not necessarily the case, we sometimes do as follows: (The difference is that the index value is a number)

$ array variable name =array (value1, value2, ..., Valuen);

3, multidimensional array of declarations

Multidimensional arrays are actually storing the array again in an array. As follows:

$content = Array (
Array (1, ' Gao MoU ', ' A company ', ' Beijing '),
Array (2, ' high some 1 ', ' Company B ', ' Beijing '),
Array (3, ' Gao MoU ', ' C Company ', ' Beijing ')
);

Traversal of arrays

1. Iterate through the array using the FOR statement

In other programming languages, the traversal of an array usually uses a For loop statement that accesses each member element of the array through the subscript of the array, but requires that the subscript of the array must be a sequential numeric index. In PHP, you can specify not only the value of a discontinuous numeric index, but also an associative array with characters as subscript. So in PHP, it's really rare to use a for statement to traverse an array. Here to bask in an example for everyone to see, we should not be unfamiliar.

The code is as follows Copy Code
<?php
Use the array () statement to declare the first record in the contact list as a one-dimensional array $contact
$contact =array (1, "Gao MoU", "a Company", "Beijing", "(015) 9582451", "gao@php.com");
Output each element in a one-dimensional array as a table
Echo ' <table border= "1" width= "align=" center ">"; Output <table> Tag definition table
Echo ' <caption>Echo ' <tr bgcolor= ' #dddddd ' > '; The row for the output table begins with a gray background

The field name of the output table in an HTML th tag
Echo ' <th> number </th><th> name </th><th> company </th><th> Address </th><th> Tel </th><th>EMAIL</th> ';
Echo ' </tr><tr> ';
For ($i =0 $i <count ($contact); $i + +) {//Use a for loop to output elements in a one-dimensional array
Echo ' <td> '. $contact [$i]. ' </td> ';
}
Echo ' </tr></table> '; Turn off markup for the output table
?>

When traversing multidimensional arrays, loop nesting is used to iterate through the layers. There is no code listed here.


2, using the foreach statement to traverse the array

Now that the FOR Loop statement is not used in PHP, let's take a look at what the good thing about foreach is.

The foreach statement has two grammatical formats, the second is minor but the first useful extension.

First syntax format:

foreach (array_expression as $value) {

Circulation body

}

Second syntax pattern:

foreach (array_expression as $key => $value) {

Circulation body

}

3, combined use of list (), each (), and while (), looping through the array

each () function

The each () function needs to pass an array as a parameter, return the key/value pair of the current element in the array, and move the array pointer back to the next element's position. A key/value pair is returned as an array of associative and index blends with four elements, with key names 0, 1, key, and value respectively. Where the value of key 0 and key is the same, the key name of the array element, and 1 and value contain the values of the array elements. Each () returns false if the internal pointer crosses the end of the array. The use of each () function is shown below:

The code is as follows Copy Code
<?php
Declare an array $contact as an argument to each () function
$contact =array ("ID" =>1, "name" => "Gao MoU", "Http://www.111cn.Net Company" => "a Company", "Address" => "Beijing");

$id =each ($contact); Returns the key/value pair of the first element in the array $contact, which is an array with 4 elements
Print_r ($id); Returns an array of $id:array ([1]=>1[value]=>1[0]=>id[key]=>id)
$name =each ($contact); Returns the key/value pair of the second element in the array rcontact, which is an array with 4 elements
Print_r ($name); Returns the array $name:array ([1]=> high certain [value]=> high certain [0]=> name [key]=> name)
$company =each ($contact);
Print_r ($company);
$address =each ($contact);
Print_r ($address);
$no =each ($contact); Has gone to the end of the array $contact, returns false
Var_dump ($no); Value of output $no: bool (FALSE)

?>

List () function

This is not a real function, but the language structure of PHP. The list () assigns values to a set of variables in one step, assigning the values in the array to some variables. The list () can only be used for arrays of numeric indices and assumes that the numeric index starts at 0. The syntax format looks like this:

List (mixed varname,mixed ...) Syntax format for =array_expression//list () statements

The list () statement differs greatly from other functions in that it does not directly receive an array as an argument. Instead, you assign the value of each element in the array to each parameter in the list () function by assigning a value to the "=" place character. The list () function converts each parameter in it to a variable that can be used directly in the script. Use the following methods:

  code is as follows copy code
  <?php
    $info =array (' coffee ', ' brown ', ' caffeine ') ); Declares an indexed array $info
    
    list ($drink, $color, $power) = $info; Converts all elements in an array to variables
    echo $drink is $color and $power makes it SPECIAL.N;//output three variable values are the values of three elements in the array
  ;   
    list ($drink, $power) = $info;//change some elements in an array to a variable
    echo $drink has $power. N "; The two change values for the output are the values of the first two elements in the array
    
    list (,, $power) = $info; Skipping the first two variables only converts the value of the third element in the array to the variable
    echo "I need $power!n";//output A variable value is the Tana three elements in the array on duty
    

Using the previous example to understand the use of the list () function, combine each () function with the list () function. The code is as follows:

The code is as follows Copy Code
<?php
$contact =array ("ID" =>1, "name" => "Http://www.111Cn.Net", "Company" => "a Company", "Address" => "Beijing");
List ($key, $value) =each ($contact); Use the each () function together with the list () function
echo "$key => $value"; Output variables $key and $value, with "=>" delimited in the middle
?>

while () looping through arrays

The syntax format for the while () loop is as follows:

while (the list ($key, $value) = each (Array_expressin)) {
Circulation body;
}

Use this combination to overwrite a one-dimensional array that was previously traversed using foreach. The code looks like this:

The code is as follows Copy Code
<?php
Declares a one-dimensional associative array $contact
$contact =array ("ID" =>1,
"Name" => "Gao MoU",
"Company" => "a Company",
"Address" => "Beijing",
"Telephone" => "(010) 987665432",
"EMAIL" => "gao@php.com"
);
Output information for each element in an array as an HTML list
Echo ' <dl> A contact information: ';
while (the list ($key, $value) = each ($contact)) {//rewrite the foreach statement into a combination of while,list () and each ()
echo "<dd> $key: $value </dd>"; Output keys for each element/duty
}
Echo ' </dl> ';
?>

4. Array internal pointer control function traversal array

For control of array pointers PHP provides the following several mole functions to be exploited.

"" Current (): is to obtain the present position of the pointer content information

Key (): The index value used to read the data that the current pointer points to

"Next (): Moves the internal pointer in the array to the next single none

Prev (): The inner pointer of an array is inverted back to a

"End (): The internal pointer to the array to the last element

"Reset (): Move the current pointer unconditionally to the first index position

The parameters of these functions are only one, which is the array itself to be manipulated. In the following example, these array pointer functions are used to control the reading order of the elements in the array. The code looks like this:

The code is as follows Copy Code
<?php
Declares a one-dimensional associative array $contact, using the "=>" character to specify the string subscript for each element
$contact = Array ("ID" =>1,
"Name" => "Gao MoU",
"Company" => "a Company",
"Address" => "Beijing",
"Telephone" => "(010) 98765432",
"EMAIL" => "gao@php.com"
);
The position of the array pointer at the first element in the array when the array is just declared
Use the key () and current () functions to pass in the array $contact, returning the key and value of the present element in the array
Echo ' first element: '. Key ($contact). ' => '. Current ($contact). ' <br> '; Output: first element: Id=>1
Echo ' first element: '. Key ($contact). ' => '. Current ($contact). ' <br> '; Array pointer not moved, output ditto

Next ($contact); Moves the pointer in an array $contact to an element once, pointing to the position of the second element
Next ($contact); Moves the pointer in an array $contact to an element once, pointing to the position of the third element
Echo ' third element: '. Key ($contact). ' => '. Current ($contact). ' <br> '; Output the key and value of the third element

End ($contact); Then move the pointer in the array $contact to the end, pointing to the last element
Echo ' last element: '. Key ($contact). ' => '. Current ($contact). ' <br> '; Outputs the key and value of the last element

Prev ($contact); Returns the pointer in the array $contact to a bit, pointing to the last second element
Echo ' Last second element: '. Key ($contact). ' => '. Current ($contact). ' <br> '; Outputs the key and value of the last second element

Reset ($contact); Resets the pointer in the array $contact to the position of the first element, pointing to the first element
Echo ' goes back to the first element '. Key ($contact). => '. Current ($contact). ' <br> '; Outputs the key and value of the first element
?>

Sorting data


The sort () function is used to sort the array cells from low to high.
The Rsort () function is used to sort the array cells from high to low.
The Asort () function is used to sort the array cells from low to high and keep the index relationship.
The Arsort () function is used to sort the array cells from high to low and to maintain an indexed relationship.
The Ksort () function is used to sort the array cells by their key names from low to high.
The Krsort () function is used to sort the array cells by their key names from high to low.

Example:

The code is as follows Copy Code
<?php
$arr = Array ("B", "A", "C");
Sort ($arr);
Print_r ($arr);
?>

Run the example output:

Array ([0] => a [1] => b [2] => c)
In this case, the $arr array cells are sorted alphabetically, and the array cells are sorted, and the key values are reassigned.

Rsort ()
The PHP Rsort () function behaves in contrast to sort (), and the array cells are sorted from highest to lowest, refer to the sort () function.

Asort ()
The PHP Asort () function is used to sort the array cells from low to high and keep the index relationship, and returns TRUE if successful, and FALSE if it fails.

Grammar:

BOOL Asort (array &array [, int sort_flags])
Optional parameters sort_flags The behavior of changing the sort, see sort ().

Example:

The code is as follows Copy Code
<?php
$arr = Array ("B", "A", "C");
Asort ($arr);
Print_r ($arr);
?>

Run the example output:

Array ([1] => a [0] => b [2] => c)

Note: The contents of this article refer to the array part of "to detail PHP", just for personal notes while learning.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.