PHP array traversal explanation for foreach list each key_PHP tutorial

WBOY
Release: 2016-07-14 10:11:41
Original
1424 people have browsed it

Explanation of php array traversal

This article mainly explains the traversal of arrays by for, foreach, list, each, key, pointer operation related functions, array_flip, array_reverse, array_walks and other functions

1.for loop traverses the array

For loop is a way to traverse arrays that can be used in almost all languages, but in PHP language, for loop is not the first choice for traversing arrays

The following is a sample code for array traversal using for loop

/*

Designed By Androidyue

Explanation of array traversal in php*/

//for loop traverses the array

//Declare an array and initialize it

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

//Use a for loop to traverse each array element, count() is used to calculate the length of the array

for($i=0;$i

//Print the value of the element of the array

echo $array[$i],"
";

}

?>

Note: There are the following limitations when using for to traverse an array:

a The array traversed must be an index array (that is, an array whose subscript is a number), and cannot be an associative array (an array whose subscript is a string)

The following code is as follows

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

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

echo $arrGoogle[$i];

}

?>

An error will be reported during runtime, similar to this error Notice: Undefined offset: 1 in D:/phpnow/htdocs/holiday/php_array_visit_summary.php on line 13. This shows that for is not suitable for traversing associative arrays

b, the array traversed by for must not only be an index array, but also the subscript must be a continuous integer. If it is not a continuous integer, a prompt will occur

The following code is as follows

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

//print_r($array);

for($i=0;$i

echo $array[$i],"
";

}

?>

In this case, a prompt similar to Notice: Undefined offset: 2 in D:/phpnow/htdocs/holiday/php_array_visit_summary.php on line 10 will also occur. Therefore, the array traversed by the for loop must be an index array and the subscripts must be consecutive. of.

2.foreach traverses the array

Foreach can be said to be a method provided by the PHP language for traversing arrays (other languages ​​may also have it). This traversal method is the first choice for PHP to traverse arrays

Foreach traversal can be like this: foreach($array as $key=>$value) contains key value elements, or it can be foreach($array as $value) which only contains values

foreach($array as $value) sample code

/*

Designed By Androidyue

Explanation of array traversal in php*/

//foreach implements traversing the array

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

//Contains only values

foreach($arrGoogle as $value){

echo $value.'
';

}

?>

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

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

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

echo 'The value of ',($key+1),'th array element is',$value,'
';

}

?>

Note that the above $value and $key are custom variables, so they can be changed 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 variables

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

Use list to implement array traversal code

//Use list traversal function

//$arrGoogle=array('brand'=>'google','email'=>'Gmail','WebBrowser'=>'Chrome','phone'=>'Android') ;//Cannot use associative 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 associative array! If it is an associative array, a prompt similar to Notice Undefined offset will appear

b If you only partially take out the value of the array, just write it like this, list(,,$chrome,)=$arrGoogle; In this way, we can remove the chrome information, but be sure to ensure that the list parameter is consistent with The number of elements in the array is the same (the number in front of the value)

c list function assignment assigns values ​​in index order

4.each function traverses the array

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

Standard syntax: array each(array input array)

Return value: Returns 4 values ​​0, 1, key, value; 0 and key contain the key name, and 1 and value contain the corresponding data

The sample code for using each to traverse an array is as follows:

//Use each function to traverse the array

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

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

$arrG=each($arrGoogle);

//Print the results, and wrap the results to clearly display the results

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

//When the pointer is at the end of the array, execute the function each again. If so, the result of executing it again will return false

$empty=each($arrGoogle);

//If the pointer cannot continue to move backward, return false

if($empty==false){

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

}

?>

Note: The parameters and return value of this function (when the pointer is not at the end of the array before executing the function) are both arrays. When the array pointer is at the end of the array before executing the function, the return value of executing the function again is false

The starting position is the first element. Every time this function is executed (normally), the pointer moves backward to the next address

5.key() traverses the array

each is the key name used to return the array

Basic syntax: mixed key (array &array)

The key function traverses the array sample code as follows

//Designed By Androidyue

//Use the key function to traverse the array

//Initialize an associative array

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

//Initialize an index array But the index array uses key to return an empty character product

$arrCN=array('Hebei','Anhui','Beijing','Guangdong','Shanghai');//key displays the string subscript of the array, if it is an index array, it is an empty character String

//print_r($arrChina);

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

echo $key,'
';

next($arrChina);

}

print_r($arrCN);//Output the index array

while($keyName=key($arrCN)){//After calling the key function and assigning a value, it is false. The while condition is not established, and 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);

}

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

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

print 'False';

}

//Call the key function on the index array to assign a value to the variable

$keyName=key($arrCN);

next($arrCN);//Move the array pointer one position backward

next($arrCN);

next($arrCN);

next($arrCN);

next($arrCN);

$keyName=key($arrCN);

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

//echo $keyName;

?>

Note: The parameters of the key function are generally associative arrays. If they are index arrays, then there is no meaning

The key function will not move the pointer. Here we call the next function. The next function is used to move the pointer backward. The following is an introduction to the next function

6. Traverse the array using functions that operate on pointers

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 also often used at the end of sorting

b.current() function

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

c end Move the pointer to the last position of the array and return the value at 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, returns false

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, it returns false

//Designed By Androidyue

//Usage of reset method Note that the following code calls a function that controls the pointer. The operation of moving the pointer will affect the result of each function

//Initialize an array. To simplify the code, declare a simple array

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

//Call each function, and the output returns an array, newline

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

echo (next($arrGoogle));//Call the next function and print the next value

$arrG=each($arrGoogle);

print_r($arrG);

print '
';

$arrGmail=each($arrGoogle);

print_r($arrGmail);

print '
';

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

//print_r($arrMore);

//echo $arrMore;

print '
';

//But if you want to continue output and repeat the above process, then 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 '
';

$arrGmail=each($arrGoogle);

print_r($arrGmail);

print '
';

?>

7.array_reverse()

This function inverts the target array elements. If preserver_key is set to true, the original mapping will be maintained, otherwise the mapping will be reset

The sample code for using this function is as follows

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

echo '

';</p>
<p>print 'array before operation';</p>
<p>print_r($arrGoogle);</p>
<p>$arrReversed=array_reverse($arrGoogle);//Do not retain previous mapping</p>
<p>print 'Result of reverse order operation without preserving_key';</p>
<p>print_r($arrReversed);</p>
<p>$arrReversedT=array_reverse($arrGoogle,1);//Keep the previous mapping</p>
<p>print 'Result of turning on preserver_key for reverse order operation';</p>
<p>print_r($arrReversedT);</p>
<p>echo'
';

?>

8.array_flip()

This function swaps the keys and values ​​of the array

The following is the usage code of this function

//Usage of array_flip() function

//Initialize an index array

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

//Initialize an associative array

$arrSohu=array('son'=>'Sogou','child'=>'Chinaren','search'=>'Sogou');//If the values ​​are the same, call the array_flip() function The same values ​​will be overwritten in order. For example, 'son'=>'Sogou' and 'search'=>'Sogou' have the same value. After using the array_flip() function, it is [Sogou] => search

//Calling the array_flip() function on the two arrays to operate and output, both can be output normally

print_r(array_flip($arrGoogle));

print '
$arrSogou's array before array_flip() function operation';

print_r($arrSohu);

print '
$arrSogou’s array without 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 passes each element in the parameter array_input to a custom function function to perform related operations. If you want to truly modify the key-value pairs of array_input, you need to use each key-value pair as a reference. Passed to 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, if the array_walk function is called to give the third value userdata, his third value Will be passed to the custom function as the third parameter.

//Designed By Androidyue

//Usage of array_walk function

//Initialize an array

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

/*

Function: A function that splices strings, concatenating the values ​​in the array and the parameters entered by the user (if no parameters are entered, the default parameter value is spliced)

Parameters: $value (custom), stores the value in the array, $key stores the key in the array, $prefix optional parameter, the user needs to assign a value to it by setting the third parameter of array_walk(), if the user No assignment, use the default, or choose as needed

Note: If the user uses reference pass-by-value, the value of the array needs to change

*/

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

$value=$prefix.$value;//The function body implements string splicing

}

array_walk($arrCorperate,'linkString');//Use array_walk() to operate the array according to the custom function

//array_walk($arrCorperate,'linkString','China');//Here is the third place to set parameters for the custom function

print_r($arrCorperate)

?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477318.htmlTechArticleExplanation of php array traversal This article mainly explains for, foreach, list, each, key, pointer operation related functions, array_flip , array_reverse, array_walks and other functions to traverse the array 1. for loop...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template