- Foreach ($ array as $ value) {// $ array indicates the array to be traversed. $ value indicates the pointer pointing to the current value of the array. as assigns a value.
- Code to executed;
- }
The foreach statement can also obtain the key name of the array, as shown below:
- Foreach ($ array as $ key => $ value ){
- Echo $ key "-" $ value ."
";
- }
2. the echo () function each () is used to split the key-value pairs of the current element of the array into a new array and use the next element as the current element. For example, Array (..., 'Robert '=> 'Bob ',...) in 'Robert '=> 'Bob', split it into Array ([1] => 'Bob', [value] => 'Bob ', [0] => 'Robert ', [key] => 'Robert') array, split into two sets (four key-value pairs in total), return, number pairs of 0 and 1, key and value name-value pairs. you can use one of them. Example:
- $ Prices = Array ('trigger' => 100, 'Oil '=> 10, 'spank S s' => 4 );
- While ($ elements = each ($ prices )){
- Echo $ elements ['key']; // echo $ elements [0];
- Echo "-";
- Echo $ elements ['value']; // echo $ element [1];
- Echo"
";
- }
Output result: Tires-100Oil-10Spank Plugs-4 3. the list () function traverses an array. the list () function can be used to break an array into a series of values. List () is often used with each. However, list () can be used together with each (), for example, list ($ key, $ value) = explode (":", $ v); list ($ key, $ value) = each ($ array); // $ key, $ value can be any name of the variable name. in this statement, the elements at the current 0, 1 position of the array returned by each are assigned to $ key, $ value variable. Example:
- $ Prices = Array ('trigger' => 100, 'Oil '=> 10, 'spank S s' => 4 );
- While (list ($ product, $ prices) = each ($ prices );){
- Echo $ product "-" $ prices;
- Echo"
";
- }
Output result: Tires-100Oil-10Spank Plugs-4 Another implementation method:
- $ Prices = Array ('trigger' => 100, 'Oil '=> 10, 'spank S s' => 4 );
- List ($ product, $ price) = $ each ($ prices );
- Echo "$ product-$ price"; // output the first array
- $ Next = $ next ($ prices); // move the pointer behind
- Echo $ next;
|