The traversal of the PHP array explains for the foreach list each key_php tutorial

Source: Internet
Author: User
Tags php language
Walkthrough of a PHP Array

This article mainly explains the For,foreach,list,each,key, the pointer operation correlation function, the array_flip, the array_reverse,array_walks and so on function's logarithmic group's traversal

1.for Looping through arrays

A For loop is a way to iterate through an array in almost any language, but in the PHP language the For loop is not the preferred choice for iterating through an array

The example code that implements the array traversal for the For loop

/*

Designed by Androidyue

Walkthrough of an array in PHP */

For loop traversal array

Declares an array and initializes

$array =array (' Google ', ' Chrome ', ' Android ', ' Youtube ', ' Gmail ');

Use the For loop to iterate through the array elements, and count () to calculate the length of the array

for ($i =0; $i<>< p=""><>

Prints the value of an array's elements

echo $array [$i], "
";

}

?>

Note: Using the FOR traversal array has the following limitations:

An array traversed by a must be an indexed array (that is, an array of numbers), not an associative array (an array labeled as a string)

such as the following code

$arrGoogle =array (' brand ' = ' Google ', ' email ' = ' Gmail ', ' WebBrowser ' + ' Chrome ', ' phone ' + ' Android ');

for ($i =1; $i <=count ($arrGoogle); $i + +) {

echo $arrGoogle [$i];

}

?>

Error at run time, similar to errors 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 traversal of associative arrays

The array that the b,for iterates over is not only an indexed array, but also a sequential integer, prompting if it is not a sequential integer

such as the following code

$array =array (1=> ' Google ',5=> ' Chrome ',7=> ' Android ',9=> ' Youtube ',12=> ' Gmail ');

Print_r ($array);

for ($i =0; $i<>< p=""><>

echo $array [$i], "
";

}

?>

This scenario also occurs with a hint 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 indexed array and the subscript must be contiguous.

2.foreach Traversal Array

foreach can be said to be a separate way for the PHP language to iterate through the array (other languages may also be available), which is the preferred way for PHP to iterate through the array

A foreach traversal can be such that a foreach ($array as $key + $value) contains a key-value element or a foreach ($array as $value) that contains only the value

foreach ($array as $value) sample code

/*

Designed by Androidyue

Walkthrough of an array in PHP */

The foreach implementation iterates through the array

$arrGoogle =array (' brand ' = ' Google ', ' email ' = ' Gmail ', ' WebBrowser ' + ' Chrome ', ' phone ' + ' Android ');

Contains only values

foreach ($arrGoogle as $value) {

echo $value. '
';

}

?>

code example for foreach ($array as $key = + $value)

$arrGoogle =array (' brand ' = ' Google ', ' email ' = ' Gmail ', ' WebBrowser ' + ' Chrome ', ' phone ' + ' Android ');

foreach ($arrGoogle as $key = = $value) {

Echo ' first ', ($key + 1), ' The value of the array element is ', $value, '
';

}

?>

Note that the above $value and $key are custom variables, so you can change the name to suit your own style as needed

3. Iterating through an array using the list function

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

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

Using list to implement the traversal code of an array

Using the list traversal function

$arrGoogle =array (' brand ' = ' Google ', ' email ' = ' Gmail ', ' WebBrowser ' + ' Chrome ', ' phone ' + ' Android '); /use associative array no

$arrGoogle =array (' Google ', ' Gmail ', ' Chrome ', ' Android ');

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

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

?>

Attention:

The array accepted by the A list function can only be an indexed array, not an associative array! If it is an associative array, a similar Notice Undefined offset hint appears

b If you just partially take out the value of the array, just follow this notation, list (,, $chrome,) = $arrGoogle, so we can remove the information from Chrome, but be sure to ensure that the list parameter is the same as the number of elements in the array (the number before the value)

C List function assignment by index order

4.each function Traversal Array

Each function returns the key-value pairs of the input array

Standard syntax: array each (array input array)

Return value: Returns 4 value 0,1,key,value, where 0 and key contain the key name, and 1 and value contain the corresponding data

The sample code that uses each to iterate through an array is as follows:

Iterating through an array using the each function

$arrGoogle =array (' Google ', ' Gmail ', ' Chrome ', ' Android ');

Use each to get the current key-value pair for the first time and move the pointer to the next position

$arrG =each ($arrGoogle);

Print results, and wrap to show results clearly

Print_r ($arrG);

print '
';

$arrGmail =each ($arrGoogle);

Print_r ($arrGmail);

print '
';

$arrChrome =each ($arrGoogle);

Print_r ($arrChrome);

print '
';

$arrAndroid =each ($arrGoogle);

Print_r ($arrAndroid);

print '
';

Executes the function again when the pointer is at the end of the array, and returns false if the result is executed again

$empty =each ($arrGoogle);

Returns False if the pointer cannot continue to move back

if ($empty ==false) {

print ' pointer is at the end of the array and cannot be moved backwards, so it returns false ';

}

?>

Note: The parameter and return value of the function (when the pointer is not at the end of the array before executing the function) is an array, and the function returns False when the function is executed again at the end of the array.

The starting position is the first element, each (normally) executes the function once, and the pointer moves backwards to the next address

5.key () traversing an array

Each is the key name used to return the array

Basic syntax: Mixed key (array &array)

The key function iterates over the array sample code as follows

Designed by Androidyue

Iterating through an array using the key function

Initialize an associative array

$arrChina =array (' a ' + = ' Hebei ', ' b ' = ' Anhui ', ' c ' = ' Beijing ', ' d ' = ' Guangdong ', ' e ' = ' Shanghai ');

Initializes an indexed array, but the index array uses key to return the empty character

$arrCN =array (' Hebei ', ' Anhui ', ' Beijing ', ' Guangdong ', ' Shanghai '),//key displays the string subscript for the array, or an empty string if the array is indexed

Print_r ($arrChina);

while ($key =key ($arrChina)) {//For associative arrays use the key method to perform

Echo $key, '
';

Next ($arrChina);

}

Print_r ($arrCN);//output an indexed array

while ($keyName =key ($arrCN)) {//Here the key function is called after the false,while condition is not set, the operation between {} is not performed

/*if (Empty ($keyName)) {

print ' The key name is empty
';

}*/

/*if ($keyName = ") {

print ' The key name is empty
';

}*/

Var_dump ($keyName);

}

To verify that the value of the return value of the key function is assigned to the variable in the indexed array. The Boolean value of the expression

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

print ' False ';

}

Call the key function on an indexed array to assign a value to a variable

$keyName =key ($arrCN);

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

Next ($arrCN);

Next ($arrCN);

Next ($arrCN);

Next ($arrCN);

$keyName =key ($arrCN);

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

Echo $keyName;

?>

Note: The parameters of the key function are generally associative arrays, and if it's an indexed array then it doesn't make any sense.

The key function does not advance the pointer movement, here we call the next function, the next function is used to push the pointer backwards, here is the introduction of the next function

6. Iterating through an array using a function that operates on the pointer

The A reset function is used to set the pointer back to the initial position of the array, and if you need to view and manipulate an array multiple times in a script, you can use this function, and this function is often used for the end of a sort

B.current () function

Returns the current value of the current array pointer position, which does not move the pointer, requiring attention to this feature

C End moves the pointer to the last position of the array, returning the value of the target position

D Next moves the pointer back one time and returns the array value of the target location, false if the current position is the last position of an array

E prev Moves the pointer forward one time and returns the array value of the target position, or false if the current position is the starting position of the array

Designed by Androidyue

Use of the Reset method note that the following code calls the function that controls the pointer, and the action of moving the pointer affects the result of each function

Initializes an array, for shorthand code, declares a simple array

$arrGoogle =array (' Google ', ' Gmail ');

The each function is called, and the output returns an array of line breaks

Echo ($arrGoogle);//Use the current function to print out the present value

Echo (Next ($arrGoogle));//Call the next function to print the next value

$arrG =each ($arrGoogle);

Print_r ($arrG);

print '
';

$arrGmail =each ($arrGoogle);

Print_r ($arrGmail);

print '
';

$arrMore =each ($arrGoogle);//returns False when the pointer cannot continue to move

Print_r ($arrMore);

Echo $arrMore;

print '
';

However, if you want to continue the output using the repeat procedure above, use the Reset function to reset the pointer to the start position, and then repeat the action above

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 '
';

$arrGmail =each ($arrGoogle);

Print_r ($arrGmail);

print '
';

?>

7.array_reverse ()

The function is to reverse the target array element and, if set Preserver_key to True, maintain the original mapping, or reset the mapping

The function uses the sample code as follows

$arrGoogle =array (' Google ', ' Gmail ', ' Android ', ' Chrome ', ' Youtube ');

Echo '

';

print ' array prior to Operation ';

Print_r ($arrGoogle);

$arrReversed =array_reverse ($arrGoogle);//Do not preserve previous mappings

print ' does not turn on preserve_key results after reverse operation ';

Print_r ($arrReversed);

$arrReversedT =array_reverse ($arrGoogle, 1);//Preserve Previous mappings

print ' Turns on preserver_key for reverse operation ';

Print_r ($arrReversedT);

Echo

';

?>

8.array_flip ()

The function is to swap the keys and values of the array

Here is the code used for the function

Use of the Array_flip () function

Initialize an array of indexes

$arrGoogle =array (' Google ', ' Chrome ');

Initialize an associative array

$arrSohu =array (' son ' = ' Sogou ', ' child ' = ' chinaren ', ' search ' = ' Sogou ');//If there is the same value call Array_flip () The function overwrites the same values in order, such as ' son ' = ' Sogou ' and ' search ' = ' Sogou ' values, using the Array_flip () function, for [Sogou] = Search

Call the Array_flip () function on two arrays and output them to output normally.

Print_r (Array_flip ($arrGoogle));

print '
$arrSogou the array ' before the Array_flip () function operation;

Print_r ($arrSohu);

print '
$arrSogou array ' after Array_flip () function operation is not performed;

Print_r (Array_flip ($arrSohu));

?>

9.array_walk function

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

The Array_walk () function is to pass each element in the parameter array array_input to the custom function functions, to do related operations, and if you want to really modify Array_input's key-value pairs, you need to pass each key-value pair as a reference to the function

The custom function must accept two input parameters, the first is the current value of the array, the second is the current key of the array, and if the call to the Array_walk function gives the third value UserData, his third value is passed to the custom function as the third argument.

Designed by Androidyue

Use of the Array_walk function

Initializes an array of

$arrCorperate =array (' Mobile ', ' Unicom ', ' Telecom ');

/*

Function: A function of stitching strings, the values in the array and the parameters entered by the user (if no parameter input stitching default parameter values)

Parameters: $value (custom), hold the values in the array, $key hold the keys in the array, $prefix optional parameters, the user needs to set the third parameter of Array_walk () to give it a value, if the user is not assigned, use the default, or as required trade-offs

Note: If the user uses a reference value, the value of the array will change

*/

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

$value = $prefix. $value;//function body Implementation string concatenation

}

Array_walk ($arrCorperate, ' linkstring ');//Use Array_walk () to manipulate the array according to the custom function

Array_walk ($arrCorperate, ' linkstring ', ' China ');//Here's the third place. To set parameters on a custom function

Print_r ($arrCorperate)

?>

http://www.bkjia.com/PHPjc/477318.html www.bkjia.com true http://www.bkjia.com/PHPjc/477318.html techarticle the traversal of the PHP array explains this article mainly explains For,foreach,list,each,key, the pointer operation correlation function, Array_flip, array_reverse,array_walks and so on the function's logarithmic group traversal 1.for follows ...

  • 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.