Home>

1.each

Look at the api first

array each (array&$array)

This is described in the api:each — returns the current key/value pair in the array and moves the array pointer forward by one step

Let's take a look at the returned array first.

<?php
$arr=array ("You", "If", "Ann", "Good", "Ben", "Yes", "Sunny", "Day");
print_r (each ($arr));
print_r (each ($arr));
echo "<hr />";
/*
return
array
(
  [1] =>you
  [value] =>you
  [0] =>0
  [key] =>0
)
array
(
  [1] =>if
  [value] =>if
  [0] =>1
  [key] =>1
)
* /
//execute the same piece of code,From "you" to "if", it means that each will be executed once,The cursor moves one step towards the end of the array
//0 and key store the key
//1 and value store the value
//So each satisfies the traversal of the array,Get the current key and value,And every time it is executed,Move one step cursor to the end
//So loop array can also be written with each
reset ($arr);
for (;$tmp=each ($arr);) {
  echo $tmp [0], "~", $tmp [1], "<br />";
}
/*
return
0 ~ you
1 ~ if
2 ~ Ann
3 ~ good
4 ~ stool
5 ~ yes
6 ~ sunny
7 ~ day
* /
?>

2.list usage

First look at what the api says

Like array (), this is not a real function,It's language structure.list () assigns a set of variables in one step.

Let's see an example:

<?php
list ($a, $b)=array (10,20);
echo $a, "~", $b, "<br />";
//return 10 ~ 20
?>

Yes, you can assign a value to a set of variables

Let's look at another example:

<?php
list ($a, $b ,, $c)=array (2 =>10,3 =>20,4 =>30,1 =>40);
echo $a, "~", $b, "~", $c, "<br />";
//return notice ~ 40 ~ 20
//When executed to $a, it returns me a notice that the array has no 0 key
?>

According to general thoughts, it should return:10 ~ 20 ~ 40

Why did I return this notice ~ 40 ~ 20?

Answer:This involves the operation mechanism of the list.list is so assigned

First:don't care about the array on the right,Look at the variables in the list,From left to right it should be $a=arr [0] $b=arr [1] $c=arr [3]

Then:assign values ​​from right to left,The order of assignment is $c=arr [3] $b=arr [1] $a=arr [0]

So $c=20 $b=40 because there is no arr [0], $a gives a warning

3. Array traversal with each and list

<?php
$arr=array ("You", "If", "Ann", "Good", "Ben", "Yes", "Sunny", "Day");
for (;list ($k, $v)=each ($arr);) {
  echo $k, "~", $v, "<br />";
}
/*
return:
0 ~ you
1 ~ if
2 ~ Ann
3 ~ good
4 ~ stool
5 ~ yes
6 ~ sunny
7 ~ day
* /
?>
php
  • Previous Tutorial for installing MongoDB and its start command mongod in Ubuntu
  • Next Summary of methods for creating objects in js