Php array traversal explanation for foreach list each key

Source: Internet
Author: User

Php array Traversal

This article mainly describes for, foreach, list, each, key, pointer operation related functions, array_flip, array_reverse, array_walks, and other functions for Array traversal.

1. for Loop traversal Array

For Loop is an array Traversal method that can be used in almost all languages. However, in php, for loop is not the first choice for Array traversal.

The following is a sample code for loop array traversal.

<? Php

/*

Designed By Androidyue

Array traversal in php */

// For Loop traversal Array

// Declare an array and initialize it.

$ Array = array ('Google ', 'chrome', 'android', 'youtube ', 'gmail ');

// Use the for loop to traverse the array elements. count () is used to calculate the length of the array.

For ($ I = 0; $ I <count ($ array); $ I ++ ){

// Print the value of an array element

Echo $ array [$ I], "<br> ";

}

?>

Note: Using for to traverse arrays has the following restrictions:

The array traversed by a must be an Index Array (that is, an array whose subscript is a number) and cannot be an associated array (an array whose subscript is a string)

See the following code

<? Php

$ ArrGoogle = array ('brand' => 'Google ', 'email' => 'gmail ', 'webbrowser' => 'chrome ', 'phone' => 'android ');

For ($ I = 1; $ I <= count ($ arrGoogle); $ I ++ ){

Echo $ arrGoogle [$ I];

}

?>

When running, an error is reported, similar to the following: Notice: Undefined offset: 1 in D:/phpnow/htdocs/holiday/php_array_visit_summary.php on line 13. This indicates that for is not suitable for Traversing associated arrays.

B. The for traversal array must satisfy both the index array and the subscript and the continuous integer. If it is not a continuous integer, a prompt is displayed.

See the following code

<? Php

$ Array = array (1 => 'Google ', 5 => 'chromi', 7 => 'android', 9 => 'youtube ', 12 => 'gmail ');

// Print_r ($ array );

 

For ($ I = 0; $ I <count ($ array); $ I ++ ){

Echo $ array [$ I], "<br> ";

}

?>

In this case, a message similar to Notice: Undefined offset: 2 in D: /phpnow/htdocs/holiday/php_array_visit_summary.php on line 10. Therefore, the for loop traversal array must be an index array and the subscript must be continuous.

2. foreach traverses the Array

Foreach can be said to be a separate method provided by the php language to traverse arrays (may be available in other languages). This Traversal method is the first choice for php to traverse arrays.

The foreach time duration can be like this: foreach ($ array as $ key => $ value) contains a key-value element or foreach ($ array as $ value) only contains a value.

Foreach ($ array as $ value) Sample Code

<? Php

/*

Designed By Androidyue

Array traversal in php */

// Foreach implements array Traversal

$ ArrGoogle = array ('brand' => 'Google ', 'email' => 'gmail ', 'webbrowser' => 'chrome ', 'phone' => 'android ');

// Contains only values

Foreach ($ arrGoogle as $ value ){

Echo $ value. '<br> ';

}

?>

Code example of foreach ($ array as $ key => $ value)

<? Php

$ ArrGoogle = array ('brand' => 'Google ', 'email' => 'gmail ', 'webbrowser' => 'chrome ', 'phone' => 'android ');

Foreach ($ arrGoogle as $ key => $ value ){

Echo 'nth ', ($ key + 1),' the value of the array element is ', $ value,' <br> ';

}

?>

Note that the above $ value and $ key are both custom variables, so you can change them to a naming method that suits your own style as needed.

3. Use the list function to traverse the Array

The list () function assigns the values in the array to the variable.

Standard Syntax: void list (mixed varname, mixed ...)

Use list to traverse the Array

<? Php

// Use the list traversal Function

// $ ArrGoogle = array ('brand' => 'Google ', 'email' => 'gmail ', 'webbrowser' => 'chrome ', 'phone' => 'android'); // it cannot be used to associate an array.

$ ArrGoogle = array ('Google ', 'gmail', 'chrome ', 'android ');

List ($ brand, $ email, $ webBrowser, $ phone) = $ arrGoogle;

Echo $ brand, $ email, $ webBrowser, $ phone;

?>

Note:

The array accepted by the list function can only be an index array, not an associated array! If it is an associated array, a message similar to Notice Undefined offset will appear.

B. If you only need to partially retrieve the value of the array, you only need to follow this method. list (, $ chrome,) = $ arrGoogle; so that we can remove chrome information, however, make sure that the list parameter is the same as the number of elements in the array (the number before the value)

C list function values are assigned by index order

4. The each function traverses the array.

The each function returns the key-value pair of the input array.

Standard Syntax: array each (array input array)

Return value: four values are returned: 0, 1, key, and value. 0 and key contain the key name, and 1 and value contain the corresponding data.

The following is an example of how to use each to traverse an array:

<? Php

// Use the each function to traverse the Array

$ ArrGoogle = array ('Google ', 'gmail', 'chrome ', 'android ');

// Use each for the first time to obtain the current key-Value Pair and move the pointer to the next position

$ ArrG = each ($ arrGoogle );

// Print the result and wrap the line to display the result clearly.

Print_r ($ arrG );

Print '<br> ';

$ ArrGmail = each ($ arrGoogle );

Print_r ($ arrGmail );

Print '<br> ';

$ ArrChrome = each ($ arrGoogle );

Print_r ($ arrChrome );

Print '<br> ';

$ ArrAndroid = each ($ arrGoogle );

Print_r ($ arrAndroid );

Print '<br> ';

// When the pointer is at the end of the array, execute the function each again. If so, the execution result returns false.

$ Empty = each ($ arrGoogle );

// If the pointer cannot be moved back, false is returned.

If ($ empty = false ){

Print 'pointer is located at the end of the array and cannot be moved backward. Therefore, false is returned ';

}

?>

Note: The parameters and return values of the function (when the pointer is not at the end of the array before the function is executed) are arrays, when the array pointer is located at the end of the array before the function is executed, the returned value of this function is false again.

The starting position is the first element. This function is executed every (normal) Time, And the pointer moves backward to the next address.

5. key () traversal Array

Each is the key name used to return the array.

Basic Syntax: mixed key (array & array)

Example code of the key function traversing array is as follows:

<? Php

// Designed By Androidyue

// Use the key function to traverse the Array

// Initialize an associated array

$ ArrChina = array ('A' => 'hebei', 'B' => 'anhui', 'c' => 'beijing ', 'D' => 'guangdong', 'E' => 'shanghai ');

// Initialize an index array, but the index array returns NULL characters using the key.

$ ArrCN = array ('hebei', 'anhui', 'beijinging', 'guangdong', 'shanghai'); // The key displays the string subscript of the array, if it is an index array, It is a null string.

// Print_r ($ arrChina );

While ($ key = key ($ arrChina) {// you can use the key method for correlated arrays to execute

Echo $ key, '<br> ';

Next ($ arrChina );

}

Print_r ($ arrCN); // output the Index Array

While ($ keyName = key ($ arrCN) {// after the key function is called here, the value is false. The while condition is not true and operations between {} are not performed.

/* If (empty ($ keyName )){

Print 'this key name is empty <br> ';

}*/

/* If ($ keyName = ''){

Print 'this key name is empty <br> ';

}*/

Var_dump ($ keyName );

}

// Verify that the return value of the key function is assigned to the index array to the Boolean value of the expression.

If ($ KeyName = key ($ arrCN) = false ){

Print 'false ';

}

// Call the key function on the index array to assign values to the variable

$ KeyName = key ($ arrCN );

Next ($ arrCN); // move the array pointer one bit backward.

Next ($ arrCN );

Next ($ arrCN );

Next ($ arrCN );

Next ($ arrCN );

$ KeyName = key ($ arrCN );

Var_dump ($ keyName); // output value and type information

// Echo $ keyName;

?>

Note: key function parameters are generally associated arrays. If they are indexed arrays, this makes no sense.

The key function does not push the pointer movement. Here we call the next function. The next function is used to push the pointer backward. The following describes the next function.

6. Use a function to traverse the Array

The a reset function is used to set the pointer back to the initial position of the array. If you need to view and process an array multiple times in a script, you can use this function, in addition, this function is often used to end the sorting.

B. current () function

Returns the value of the current array pointer position. This function does not move the pointer. Pay attention to this feature.

C end moves the pointer to the last position of the array and returns the value of the target position.

D next moves the pointer backward once and returns the array value of the target position. If the current position is the last position of the array, false is returned.

E prev moves the Pointer Forward once and returns the array value of the target position. If the current position is the starting position of the array, false is returned.

<? Php

// Designed By Androidyue

// Use the reset method. Note that the following code calls the pointer control function. Moving the pointer affects the result of the each function.

// Initialize an array and declare a simple array for short code

$ ArrGoogle = array ('Google ', 'gmail ');

// Call the each function, and the output returns the array line feed.

Echo (current ($ arrGoogle); // use the current function to print the current value.

Echo (next ($ arrGoogle); // call the next function to print the next value.

$ ArrG = each ($ arrGoogle );

Print_r ($ arrG );

Print '<br> ';

$ ArrGmail = each ($ arrGoogle );

Print_r ($ arrGmail );

Print '<br> ';

$ ArrMore = each ($ arrGoogle); // returns false if the pointer cannot be moved.

// Print_r ($ arrMore );

// Echo $ arrMore;

Print '<br> ';

// However, if you want to continue the output, use the reset function to reset the pointer to the starting position, and then repeat the above operation.

Reset ($ arrGoogle );

Echo (end ($ arrGoogle); // call the end function to move the pointer to the last position of the array and return the value.

Echo (prev ($ arrGoogle); // call the prev function to move the Pointer Forward and return the value

$ ArrG = each ($ arrGoogle );

Print_r ($ arrG );

Print '<br> ';

$ ArrGmail = each ($ arrGoogle );

Print_r ($ arrGmail );

Print '<br> ';

?>

7. array_reverse ()

This function is used to reverse the elements of the target array. If preserver_key is set to true, the original ing is maintained; otherwise, the ing is reset.

The sample code for using this function is as follows:

<? Php

$ ArrGoogle = array ('Google ', 'gmail', 'android', 'chrome ', 'youtube ');

Echo '<pre> ';

Print 'array before operations ';

Print_r ($ arrGoogle );

$ ArrReversed = array_reverse ($ arrGoogle); // The previous ing is not retained.

Print 'result after preserve_key is not enabled for reverse-order operations ';

Print_r ($ arrReversed );

$ ArrReversedT = array_reverse ($ arrGoogle, 1); // retain the previous ing

Print 'result of enabling preserver_key for reverse operations ';

Print_r ($ arrReversedT );

Echo '</pre> ';

?>

8. array_flip ()

This function swaps the keys and values of an array.

The following is the code for using the function.

<? Php

// Use the array_flip () function

// Initialize an Index Array

$ ArrGoogle = array ('Google ', 'chrome ');

// Initialize an associated array

$ ArrSohu = array ('son' => 'sogou', 'Child '=> 'chinaren', 'search' => 'sogou '); // if the value is the same, the array_flip () function will overwrite the same value in order, for example, 'son' => 'sogou' and 'search' => 'sogou' have the same value. After using the array_flip () function, it is [Sogou] => search

// Call the array_flip () function to operate the two arrays and output them. Both Arrays can be output normally.

Print_r (array_flip ($ arrGoogle ));

Print '<br> $ arrSogou array before array_flip () function operation ';

Print_r ($ arrSohu );

Print '<br> $ array after arrSogou does not perform the array_flip () function operation ';

Print_r (array_flip ($ arrSohu ));

?>

9. array_walk Function

Boolean array_walk (array input_array, callback function [, mixed userdata])

The array_walk () function transmits each element in the array_input parameter array to the custom function for related operations, if you want to modify the key-value pair of array_input, you must pass each key-value pair as a reference to the function.

The user-defined function must accept two input parameters. The first is the current value of the array and the second is the current key of the array. If the array_walk function is called, the third value userdata is provided, the third value is passed to the UDF as the third parameter.

<? Php

// Designed By Androidyue

// Use the array_walk Function

// Initialize an array

$ ArrCorperate = array ('mobile ', 'unicom', 'telecom ');

/*

Function: a concatenation string function that concatenates values in the array with user-input parameters (if no parameter is input, the default parameter value is spliced)

Parameter: $ value (custom), stores the values in the array, $ key stores the keys in the array, $ prefix optional parameter, you need to set array_walk () assign a value to the third parameter. If the user does not assign a value, use the default value, or choose as needed.

Note: If you use reference to pass a value, the value of the array must be changed.

*/

Function linkString (& $ value, $ key, $ prefix = 'cn '){

$ Value = $ prefix. $ value; // The function body concatenates strings.

}

Array_walk ($ arrCorperate, 'linkstring'); // use array_walk () to operate the array according to the custom function

// Array_walk ($ arrCorperate, 'linkstring', 'China'); // set parameters for the custom function in the third part.

Print_r ($ arrCorperate)

?>

 

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.